开发者

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 t开发者_运维技巧imestamp, 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;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜