In the table below, how do I get just the most recent record of id=1
based on the signin column and not all 3 records?
+----+---------------------+---------+
| 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 |
+----+---------------------+---------+
I had a similar problem. I needed to get the last version of page content translation, in other words - to get that specific record which has highest number in version column. So I select all records ordered by version and then take the first row from result (by using LIMIT clause).
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 beNULL
values: the row with the latest not-nullsignin
.To get
NULL
values first:Related:
The SQL standard does not explicitly define a default sort order for
NULL
values. The behavior varies quite a bit across different RDBMS. See: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:Simple Way To Achieve
I know it's an old question You can also do something like
In above, query the first record will be the most recent record.
For only one record you can use something like
Above query will only return one latest record.
Cheers!
Use the aggregate
MAX(signin)
grouped by id. This will list the most recentsignin
for eachid
.To get the whole single record, perform an
INNER JOIN
against a subquery which returns only theMAX(signin)
per id.