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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-29 08:35:11878browse

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

Identifying the Most Recent Row for a Given ID:

The provided table contains multiple rows with varying signin timestamps for different id values. The objective here is to retrieve the most recent row, based on the signin column, for a specific id value (id=1).

Using MAX() Aggregate and GROUP BY:

One approach to accomplish this is by using the MAX() aggregate function along with a GROUP BY clause. The following query aggregates the maximum signin timestamp for each unique id:

SELECT
  id,
  MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id;

This query produces a table with two columns: id and most_recent_signin. The most_recent_signin column contains the most recent signin timestamp for each id.

Retrieving the Complete Record:

However, if the goal is to retrieve the complete record (including all columns) for the most recent row with>

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;

This query performs an INNER JOIN between the tbl table and a subquery (ms) that selects the maximum signin timestamp for each id. It then filters the results to include only the row with>

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

Statement:
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