我正在建立一个讨论区......我有一个包含帖子的表和另一个包含评论的表...外国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
查询工作正常,但问题是没有选择没有评论的帖子。如果他们有评论,我想显示帖子而不是他们,但我想按评论数量对它们进行排序。
答案 0 :(得分:3)
使用LEFT加入。你的From / where关节相当于INNER 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
答案 1 :(得分:2)
在评论表
试试这个:
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
INNER JOIN user u ON p.owner_id = u.id
LEFT JOIN comments c ON p.post_id = c.post_id
GROUP BY p.post_id
ORDER BY number DESC;