以下是存储我的数据的3个表:
答案
answer_id | question_id | answer
问题
question_id | question
users_answers
user_answer_id | answer_id | question_id
我在实践中要做的事情:
对于给定的问题,请收集所有答案,并计算有多少人回答了A或B。 这里的重点是,即使没有人选择它作为可能的好答案,我也需要所有答案。
这是我进行的查询:
SELECT q.question_id,
q.question,
a.answer_id,
a.answer
FROM questions AS q
JOIN answers AS a ON
q.question_id = a.question_id
JOIN users_answers ON
a.answer_id = users_answers.answer_id
WHERE q.question_id = 19
这是我的实际结果(带有示例):
question_id | question | answer_id | answer
19 'blabla' 12 'C blabla'
19 'blabla' 12 'C blabla'
19 'blabla' 10 'A blabla'
19 'blabla' 13 'D blabla'
没有用户给出“ B blabla”作为可能的好答案,但是我的结果中仍然需要此结果。
我该怎么做?
非常感谢您
答案 0 :(得分:0)
SELECT questions.question_id,
questions.question,
answers.answer_id,
answers.answer,
(SELECT Count(users_answers.user_answer_id)
FROM users_answers
WHERE users_answers.question_id = 1
AND users_answers.answer_id IN ( 1, 2 )) AS
total_people_answered_anserA_B
FROM users_answers
INNER JOIN questions
ON questions.question_id = users_answers.question_id
INNER JOIN answers
ON answers.answer_id = users_answers.answer_id
WHERE users_answers.question_id = 1;