我有一个帖子的数据库表。我有另一个包含注释的db表,其中包含comment_id(ai)列和post_id附加到的列。
我想查询所有帖子一次的查询列表,按上次发布的评论排序。
问题是我无法找出sql查询来做到这一点。无论我尝试什么,我都会列出所有评论。我对mysql非常熟练或经验丰富,但我尝试使用不同的"加入"。有没有办法做到这一点?
答案 0 :(得分:1)
SELECT posts.*, comments.last_one
FROM posts
LEFT JOIN
(SELECT MAX(updated) as last_one, post_id
FROM comments
GROUP BY post_id
) as comments
ON comments.post_id = posts.id
ORDER BY comments.last_one DESC
答案 1 :(得分:0)
SELECT distinct p.* FROM posts as p, comments as c
WHERE p.post_id = c.post_id ORDER BY c.time DESC
我刚刚假设你的关系模式。您可能需要调整查询。
替代方法:使用last_comment_time作为字段创建视图。
CREATE VIEW posts AS
(SELECT *, (SELECT time FROM comments WHERE post_id = p.post_id ORDER BY time DESC LIMIT 1) as last_comment_time
FROM posts as p);