简体   繁体   中英

MySQL: Multiple Counts within the same LEFT JOIN table not working

I have these 3 tables:

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

I am trying a query to get the following results:

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

So far i am good with everything except the #3, ie replies count only (comments.parent_comment != 0)

This is the query:

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

The result i am having is "totalReplies" count is similar to "totalComments" count.

Any ideas how can i get this to work by getting correct totalReplies count?

Thanks!

COUNT() will count zeros. Use SUM(), a la:

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

I think there's a couple things going on here. The structure of your case statement as mentioned above could use a reworking

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

Try this. It takes care of your selective group by, and your COUNT misinterpretation on CASE struct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM