mysql Group by max id&左边加入另一张桌子

时间:2014-02-10 07:13:00

标签: mysql

SELECT * FROM posts 
WHERE post_id IN (SELECT MAX(post_id) FROM posts GROUP BY album_id) 
AS T
LEFT JOIN album 
ON T.album_id=album.album_id

我有2个表,第一个我需要通过album_id获取最大post_id组

比我需要离开加入专辑ON album_id

post_id | album_id      album_id  |  album_title
1         0             0            abc
2         1             1            def
3         1

结果应该是

post_id   |  album_id   |  album_title
1            0             abc
3            1             def

1 个答案:

答案 0 :(得分:1)

尝试此查询 -

SELECT * FROM
  posts p1
JOIN (SELECT album_id, MAX(post_id) post_id FROM posts GROUP BY album_id) p2
  ON p1.album_id = p2.album_id AND p1.post_id = p2.post_id