2013-06-04 33 views
0

我有這3個表:MySQL的:相同的左內多計數JOIN表不工作

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」 count類似於「totalComments」 count。

任何想法如何通過獲得正確的totalReply數來得到這個工作?

謝謝!

回答

2

COUNT()會計數爲零。使用SUM(),a:

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

謝謝!這工作得很好:D –

+0

我剛剛發現一個小問題,它的'totalReplies'值始終是1,即使沒有對帖子發表任何評論,'totalReplies'出現爲1而不是0.任何想法? –

+0

更精確,如果'totalComments'計數爲0,則'totalReplies'計數變爲1.如果'totalComments'計數> 0,那麼'totalReplies'計數正常工作,並顯示0或正確的答覆數。 –

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 

試試這個。它會照顧你的選擇性組合,並且你的COUNT會在CASE結構上誤解。

+0

謝謝你的解決方案,但是@nw的回答很快就適用了。 –

+0

感謝upvote – Hituptony

+0

我剛剛嘗試過您的解決方案(因爲@nw的解決方案在顯示totalReplies分鐘時總是1,而不是在沒有顯示0的地方有點問題),您的解決方案將總計評估數和總計回覆次數加倍。有任何想法嗎? –