2016-03-16 64 views
0

以下查詢返回正確的latest_time,但相應的字段不正確。如何獲得給定MAX值的匹配字段?mysql組通過不返回正確的對應行

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

回答

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` 
+0

謝謝,工作出色! – blackswan