1

我正在建立一个讨论板...我有一个包含帖子的表格和另一个包含评论的表格...外国 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 

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

4

2 回答 2

3

使用左连接。您的 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 
于 2013-01-16T16:54:49.143 回答
2

在评论表上使用LEFT 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 
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;
于 2013-01-16T16:54:30.257 回答