Home > Database > Mysql Tutorial > How to Retrieve the Most Recent Row for a Given ID in SQL?

How to Retrieve the Most Recent Row for a Given ID in SQL?

Barbara Streisand
Release: 2025-01-01 07:45:11
Original
804 people have browsed it

How to Retrieve the Most Recent Row for a Given ID in SQL?

Retrieving the Most Recent Row for a Given ID

In a situation where a database table contains multiple rows for the same ID, it may be necessary to extract only the most recent one. This article addresses how to achieve this in SQL.

Using the provided table as an example:

+----+---------------------+---------+
| id | signin              | signout |
+----+---------------------+---------+
|  1 | 2011-12-12 09:27:24 | NULL    |
|  1 | 2011-12-13 09:27:31 | NULL    |
|  1 | 2011-12-14 09:27:34 | NULL    |
|  2 | 2011-12-14 09:28:21 | NULL    |
+----+---------------------+---------+
Copy after login

Aggregate MAX(signin) Grouped by ID

To obtain the most recent signin time for each ID, group the rows by ID and aggregate with MAX(signin). This will provide a list of IDs with their corresponding latest signin times.

SQL Query:

SELECT 
 id, 
 MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id
Copy after login

INNER JOIN Against a Subquery

To retrieve the entire most recent row for a specific ID (e.g., ID=1), use an INNER JOIN against a subquery that calculates the MAX(signin) per ID. Then, filter the results based on the desired ID.

SQL Query:

SELECT 
  tbl.id,
  signin,
  signout
FROM tbl
  INNER JOIN (
    SELECT id, MAX(signin) AS maxsign FROM tbl GROUP BY id
  ) ms ON tbl.id = ms.id AND signin = maxsign
WHERE tbl.id=1
Copy after login

The above is the detailed content of How to Retrieve the Most Recent Row for a Given ID in SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template