如果我有一个如下所示的MySQL表:
id | cat_id | name | date
------------------------------------
1 | 1 | suzy | 2011-09-15
2 | 2 | andy | 2011-10-01
3 | 1 | dony | 2010-12-25
4 | 3 | harry | 2010-01-05
5 | 2 | matty | 2011-06-01
6 | 3 | samy | 2010-11-02
7 | 1 | honey | 2011-10-03
如何选择是否需要结果:
cat_id | id |
-------------
1 | 7 |
2 | 2 |
3 | 6 |
答案 0 :(得分:1)
SELECT cat_id, id
FROM mytable t
WHERE NOT EXISTS (
SELECT *
FROM mytable
WHERE cat_id = t.cat_id
AND date > t.date
)
答案 1 :(得分:0)
SELECT cat_id, id
FROM (SELECT cat_id, name
FROM table
ORDER BY date DESC) AS h
GROUP BY cat_id
ORDER BY cat_id ASC
替换table
答案 2 :(得分:0)
尝试此查询 -
SELECT c1.cat_id, c1.id FROM catalog c1
JOIN (SELECT cat_id, MAX(date) last_date FROM catalog GROUP BY cat_id) c2
ON c1.cat_id = c2.cat_id AND c1.date = c2.last_date;