mysql组通过不返回正确的对应行

时间:2016-03-16 21:10:23

标签: mysql group-by

以下查询返回正确的latest_time,但相应的字段不正确。如何获得给定MAX值的匹配字段?

select `id`,`value1`,`value2`, MAX(`timestamp`) as `latest_time` 
   from `table` 
   group by `value1`

1 个答案:

答案 0 :(得分:1)

SELECT中显示的非聚合列具有不确定的值。您需要自联接才能获得所需的值:

select t1.`id`, t1.`value1`, t1.`value2`, t1.`timestamp`
from `table` as t1
join (
   select `value`, MAX(`timestamp`) as `latest_time` 
   from `table` 
   group by `value1`
) as t2 on t1.`value1` = t2.`value1` and t1.`timestamp` = t2.`latest_time`