2014-02-07 41 views
0

我有两个表:如何通过连接计数在mysql中订购数据?

posts : id,title,content,show,created_at 

comments: id,post_id,created_at 

我想订购由最多评论的帖子。

SELECT *, COUNT(comments.id) AS total_comments 
FROM comments LEFT JOIN posts ON posts.id = comments.post_id 
WHERE posts.show = '1' 
GROUP BY complains.id 
ORDER BY total_comments DESC 

问题是没有出现带有0条评论的帖子。 任何帮助将不胜感激。

+0

你在问什么?如何对'count'进行排序,或者为什么没有出现带有0条评论的帖子? – helion3

+4

你需要'LEFT JOIN'对帖子的评论,而不是评论。这样,将显示具有零评论的帖子。 – Rainbolt

+0

什么是抱怨?这是应该读评论? – dave

回答

2

随着你的加入以上,你错误地加入获得有帖子的commens 你应该已经做了一个正确的加入或交换如下左连接的表。

Select *, COUNT(comments.id) as total_comments 
FROM posts 
LEFT outer JOIN comments on posts.id = comments.post_id 
WHERE posts.show = '1' 
GROUP BY posts.id 
ORDER BY total_comments DESC 
1

您需要做一个RIGHT JOIN而不是LEFT JOIN。或者交换LEFT JOIN子句中的表。

+1

+1来解释问题,而不是为他写出解决方案。可悲的是,Nihat只是在没有一丝解释的情况下为他做了功课问题。 – Rainbolt

+1

我是新来的,你可以从我的个人资料中看到。下次我会做得更好。感谢您的评论。 – Nihat

+1

@Nihat成为一个男人的方式。我现在感觉像个混蛋!我们都在这里只是为了帮助人们。我诚恳地为我粗鲁的评论道歉。 – Rainbolt

1

虽然有很多方法可以解决这个问题,但我认为这段代码很容易阅读和理解。

可以将LEFT JOIN中的查询复制出来并自行运行以帮助调试。然后,将该结果集加入到帖子表中并对结果进行排序。

SELECT p.*, IFNULL(c.total_comments, 0) as total_comments 
FROM posts p 
LEFT JOIN (select post_id, count(post_id) as total_comments from comments group by post_id) as c ON p.id = c.post_id 
WHERE p.show = '1' 
ORDER BY c.total_comments DESC