我想知道有多少用户回答了一个问题,所以我提出了这个问题:
SELECT answer.idAnswer,
answer.title,
answercategory.label,
(SUM(1)) as nbAnswer
FROM ANSWER
INNER JOIN answerCategory ON answer.idAnswerCategory = answercategory.idAnswerCategory
LEFT JOIN answerUser ON answer.idAnswer = answerUser.idAnswer
GROUP BY answer.idAnswer
它几乎正常工作,唯一不起作用的是,如果没有人回答问题,它会给我“一个”答案(这意味着即使在answerUser中没有记录)。在这种情况下,我想零而不是一个。如果我添加“-1”,当有一个答案时,我会得到零。知道如何纠正这个问题吗?
答案 0 :(得分:2)
使用COUNT(answerUser.idAnswer)
代替SUM(1)
。 Count将忽略LEFT JOIN创建的NULL行。
答案 1 :(得分:1)
使用COUNT(*)
代替SUM(1)
。
答案 2 :(得分:1)
SELECT answer.idAnswer, answer.title, answercategory.label, count(*) as nbAnswer
FROM answer
INNER JOIN answerCategory on answer.idAnswerCategory = answercategory.idAnswerCategory
LEFT JOIN answerUser ON answer.idAnswer = answerUser.idAnswer
GROUP BY answer.idAnswer