假设我有这个问题:
SELECT report_id, time_sent
FROM report_submissions
WHERE report_id IN (1,2,3,4,5,6)
ORDER BY report_id ASC, time_sent DESC
有了这个结果:
report_id time_sent
1 2
1 1
2 4
2 3
3 4
我想更改该查询,以便获得带有max(time_sent)的DISTINCT report_id,例如:
report_id time_sent
1 2
2 4
3 4
如何以最有效的方式实现这一目标?感谢。
答案 0 :(得分:2)
SELECT report_id, max(time_sent)
FROM report_submissions
WHERE report_id IN (1,2,3,4,5,6)
GROUP BY report_id
ORDER BY report_id ASC
答案 1 :(得分:0)
DISTINCT
是一个懒惰的GROUP BY
!
SELECT report_id, max(time_sent)
FROM report_submissions
WHERE report_id IN (1,2,3,4,5,6)
GROUP BY report_id
ORDER BY report_id ASC, max(time_sent) DESC
答案 2 :(得分:0)
您需要使用group by
请参阅:http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html