MySQL:同一LEFT JOIN表中的多个计数不起作用

时间:2013-06-04 18:28:51

标签: mysql left-join

我有这3张桌子:

1. posts (num, title, createdDate)
2. comments (num, post_num, parent_comment)
3. likes (comment_num)

我正在尝试查询以获得以下结果:

1. all posts
2. comments count including replies
3. replies count only (comments.parent_comment != 0)
4. total likes count
5. total participants in a post

到目前为止,我对除#3之外的所有内容都很满意,即回复只计算(comments.parent_comment!= 0)

这是查询:

SELECT 
posts.num, 
posts.title, 
DATEDIFF(NOW(),posts.createdDate) as NumOfDays,
COUNT( comments.num)  AS totalComments,
COUNT( CASE WHEN comments.parent_comment=0 THEN 0 ELSE comments.parent_comment END)  AS totalReplies,


COUNT( likes.comment_num  ) AS totalLikes,
COUNT( DISTINCT comments.member_num)  AS participants,
cms_uploads.urlPath

FROM posts
LEFT JOIN comments ON comments.post_num = posts.num
LEFT JOIN likes ON likes.comment_num = comments.num


GROUP BY posts.num
ORDER BY totalComments DESC

我的结果是“totalReplies”计数类似于“totalComments”计数。

任何想法如何通过获得正确的totalReplies计数来实现这一点?

谢谢!

2 个答案:

答案 0 :(得分:2)

COUNT()将计为零。使用SUM(),la:

SUM( CASE WHEN comments.parent_comment = 0 THEN 1 ELSE 0 END)  AS totalReplies,

答案 1 :(得分:1)

我认为这里有几件事情要发生。如上所述,您的案例陈述的结构可以使用重新加工

SELECT 
posts.num, posts.title, urlpath(? dont see this in any table),  DATEDIFF(NOW(),posts.createdDate) as NumOfDays, 
SUM( comments.num)  AS totalComments,
SUM( CASE WHEN comments.parent_comment=0 THEN 1 ELSE 0 END)  AS totalReplies,
SUM( likes.comment_num  ) AS totalLikes,
COUNT( DISTINCT comments.member_num)  AS participants, 
FROM posts
LEFT JOIN comments ON comments.post_num = posts.num
LEFT JOIN likes ON likes.comment_num = comments.num
GROUP BY posts.num, posts.title, NumOfDays
ORDER BY totalComments DESC

试试这个。它会照顾您的选择性组,以及您对CASE结构的COUNT误解。