我希望能够在应用程序的每个房间检索用户发布的最后一篇文章。但是,根据我构建的查询,我正在检索第一个查询?
表格看起来像这样
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
谢谢
答案 0 :(得分: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,包含您的查询和我的查询。