我有一张表:
id|val|updated 1 | 31|2012-01-12 1 | 34|2012-01-15 2 | 41|2012-01-15 3 | 44|2012-01-15 4 | 66|2012-01-01
我需要选择具有最大更新值的id和val。因此,对于此表,结果应为:
1| 34| 2012-01-15 2| 41| 2012-01-15 3| 44| 2012-01-15 4| 66| 2012-01-01
这需要MAX()在与主表连接的子查询中进行汇总。
MAX()
SELECT tbl.id, tbl.val, tbl.updated FROM tbl JOIN ( /* Subquery gets MAX(updated) per id to JOIN against */ SELECT id, MAX(updated) as updated FROM tbl GROUP BY id ) t2 ON tbl.id = t2.id AND tbl.updated = t2.updated