2013-08-29 53 views
0

我總是看到COUNT()與*作爲參數使用,GROUP BY決定什麼是要計算的,但我相信你可以計算不同的東西必須做子查詢,分組,然後加入(這就是我現在正在做的)。如何統計多個表中的多個事物

讓我們建立一個例子出來,這樣一個簡化版本:

Table Question 
idQuestion | title | idUser 

Table Answer 
idAnswer | idQUestion | text | idUser 

Table Vote 
idVote | idAnswer | type | idUser 

Table Comment 
idComment | idAnswer | text | idUser 

要知道所有的答案多少評論和投票有我做:

SELECT idAnswer, votes, comments FROM 
    (SELECT idAnswer, count(*) AS votes FROM Answer A 
     JOIN Vote B ON A.idAnswer=B.idAnswer 
    GROUP BY idAnswer) AS X 
JOIN 
    (SELECT idAnswer, count(*) AS comments FROM Answer A 
     JOIN Comment B ON A.idAnswer=B.idAnswer 
    GROUP BY idAnswer) AS Y 
ON X.idAnswer=Y.idAnswer 

可以這樣沒有完成子選擇?什麼是通過避免它們來實現的?

如何計算同一查詢中的負面投票和正面投票?

+0

順便說一下,您的id'nswer缺失您的投票表 – Cruncher

回答

1
SELECT idAnswer, COUNT(DISTINCT VOTE.idVote), COUNT(DISTINCT comments) 
FROM Answer 
LEFT JOIN COMMENT ON Answer.idAnswer = Comment.idAnswer 
LEFT JOIN VOTE ON Answer.idAnswer = Vote.idAnswer 
GROUP BY idAnswer 

至於你的問題的第二部分,感謝Andriy M!

SELECT 
    Answer.idAnswer, 
    COUNT(DISTINCT CASE WHEN VOTE.type = 'up' THEN VOTE.idVote END) AS upvotes, 
    COUNT(DISTINCT CASE WHEN VOTE.type = 'down' THEN VOTE.idVote END) AS downvotes, 
    COUNT(DISTINCT comments) as comments 
FROM Answer 
LEFT JOIN COMMENT ON Answer.idAnswer = Comment.idAnswer 
LEFT JOIN VOTE ON Answer.idAnswer = Vote.idAnswer 
GROUP BY Answer.idAnswer 
+1

您應該使用左連接。如果還沒有留言,該怎麼辦? –

+0

啊,是的,你是對的。謝謝 – Cruncher

+0

沒有「左內連接」;-)「左連接」或「左外連接」都是正確的。 –