我一直看到 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
这可以在没有子选择的情况下完成吗?避免它们有什么收获吗?
你怎么能在同一个查询中计算反对票和赞成票?