0

我一直看到 COUNT() 与 * 一起用作参数,而 GROUP BY 确定要计算的内容,但我相信您可以计算不同的事物,而无需进行子查询、分组,然后加入(其中是我现在正在做的)。

让我们用 SO 的简化版本构建一个示例:

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

这可以在没有子选择的情况下完成吗?避免它们有什么收获吗?

你怎么能在同一个查询中计算反对票和赞成票?

4

1 回答 1

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
于 2013-08-29T17:34:02.970 回答