0

我有这 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”计数。

有什么想法可以通过获得正确的总回复数来使其正常工作吗?

谢谢!

4

2 回答 2

2

COUNT() 将计算零。使用 SUM(),例如:

SUM( CASE WHEN comments.parent_comment = 0 THEN 1 ELSE 0 END)  AS totalReplies,
于 2013-06-04T18:32:50.217 回答
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 误解。

于 2013-06-04T18:38:13.347 回答