我正在建立一个讨论板。。。我有一个包含帖子的表和另一个包含评论的表。。。外部id是post_id。现在,我试着根据每个评论的数量来对文章进行排序。我当前使用的查询:

SELECT username, posts.post_id, category_id, UNIX_TIMESTAMP(posts.datetime) AS datetime, posts.body, posts.owner_id, COUNT(comment_id) AS number
FROM posts, comments, user
WHERE posts.post_id = comments.post_id AND posts.owner_id = user.`id`
GROUP BY comments.post_id
ORDER BY number DESC

查询工作正常,但问题是没有选择评论的帖子。我想显示不介意他们是否有评论的帖子,但我想按评论数量排序。

最佳答案

使用左连接。您的From/where joint等同于内部JOIN:

SELECT username, p.post_id, category_id, UNIX_TIMESTAMP(p.datetime) AS datetime,
   p.body, p.owner_id, COUNT(comment_id) AS number
FROM posts p
LEFT JOIN comments c ON p.post_id = c.post_id
LEFT JOIN user u ON p.owner_id = u.`id`
GROUP BY c.post_id
ORDER BY number DESC

关于mysql - 当另一个表的行数为0时未获得结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14363440/

10-16 06:49