简体   繁体   中英

How to query the most recent row for each value in column X?

I'm trying to query the most recent row for each value in a column X.

My current attempt is:

SELECT max(mytimestamp), mytable.* FROM mytable GROUP BY X

but while the first column in the result contains the latest timestamp, the other columns are not from the most recent row.

How do I fix that?

SELECT M.*
from
(
 SELECT X, max(mytimestamp) MaxT
 FROM mytable
 GROUP BY X
) N
inner join mytable M on M.X = N.X and M.mytimestamp = N.MaxT

While MySQL allows you to mix aggregate and non-aggregate columns in a GROUP BY query.. please don't. Consider the scenario similar to what you have:

 SELECT max(mytimestamp) MaxT, min(mytimestamp) MinT, mytable.*
 FROM mytable
 GROUP BY X

Think about it and let me know which record the columns should come from (hint: max or min).

This only involves one table? Then why not this:

select * from mytable order by mytimestamp desc limit 1

I dont think you need the group by:

SELECT max(timestamp), mytable.* FROM mytable limt 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM