0

I want to know how many users answerd a question, so I made that query :

    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

Its almost working, the only thing that doesn't work is that it's giving me "one" answer if nobody answered the question (it means even if there are no records in answerUser). I would like to have zero instead of one in that case. If I add a "-1", when there is one answer, I'll get zero. Any idea how I can correct that?

1
  • Is this MySQL or SQLite? Commented Feb 26, 2011 at 4:25

3 Answers 3

2

Use COUNT(answerUser.idAnswer) instead of SUM(1). Count will ignore the NULL rows created by the LEFT JOIN.

Sign up to request clarification or add additional context in comments.

Comments

1

Use COUNT(*) instead of SUM(1).

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.