1

我希望能够检索用户在应用程序中的每个房间发布的最后一篇文章。但是,通过我建立的查询,我总是检索第一个?

桌子看起来像这样

Rooms
id|name|subname 

Posts
id|title|description|id_room|date_posted

我在这里错过了什么或做错了什么?

SELECT * FROM rooms AS rm
INNER JOIN posts AS pst ON pst.id_room = rm.id
WHERE pst.id = ( 
SELECT MAX( pst.id ) FROM posts ) 
GROUP BY rm.id

谢谢

4

1 回答 1

2

类似的东西应该更好(您的查询只检索 MAX pst.id,而不是按房间的 MAX pst.id)

select * from rooms as rm
inner join posts as pst on pst.id_room = rm.id
where pst.id in (select max(pst.id) from posts
                 group by pst.id_room)

简化SqlFiddle,带有您的查询和我的查询。

于 2013-04-18T14:40:32.890 回答