Get most recent row for given ID
Use the aggregate MAX(signin)
grouped by id. This will list the most recent signin
for each id
.
SELECT
id,
MAX(signin) AS most_recent_signin
FROM tbl
GROUP BY id
To get the whole single record, perform an INNER JOIN
against a subquery which returns only the MAX(signin)
per id.
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
SELECT *
FROM tbl
WHERE id = 1
ORDER BY signin DESC
LIMIT 1;
The obvious index would be on (id)
, or a multicolumn index on (id, signin DESC)
.
Conveniently for the case, MySQL sorts NULL
values last in descending order. That's what you typically want if there can be NULL
values: the row with the latest not-null signin
.
To get NULL
values first:
ORDER BY signin IS NOT NULL, signin DESC
You may want to append more expressions to ORDER BY
to get a deterministic pick from (potentially) multiple rows with NULL
.
The same applies without NULL
if signin
is not defined UNIQUE
.
Related:
- mysql order by, null first, and DESC after
The SQL standard does not explicitly define a default sort order for NULL
values. The behavior varies quite a bit across different RDBMS. See:
- https://docs.mendix.com/refguide/null-ordering-behavior
But there are the NULLS FIRST
/ NULLS LAST
clauses defined in the SQL standard and supported by most major RDBMS, but not by MySQL. See:
- SQL how to make null values come last when sorting ascending
- Sort by column ASC, but NULL values first?