我有情况下,用户,我需要选择该回答这个问题在SQL 我的表正确看用户的每一个问题数量一样让每一个问题,许多答对
table 1: questionnaire_question
id - question_text - thecorrectAnswer
table 2 :questionnaire_answers
id - user_id - question_id - user_answer - correct
正确的列有用户回答值为0或1的正确与否
我有情况下,用户,我需要选择该回答这个问题在SQL 我的表正确看用户的每一个问题数量一样让每一个问题,许多答对
table 1: questionnaire_question
id - question_text - thecorrectAnswer
table 2 :questionnaire_answers
id - user_id - question_id - user_answer - correct
正确的列有用户回答值为0或1的正确与否
使用LEFT JOIN
,GROUP BY
和COUNT
select
q.id,
count(distinct a.user_id) cnt -- can be replaced with count(*)
-- if a user has only at max one correct answer
-- for a given question
from questionnaire_question q
left join questionnaire_answers a
on q.id = a.question_id
where correct = 1
group by q.id;
您可以加入表和count
一个case
表达,检查正确性:
SELECT q.id, cnt
FROM questionnaire_question q
JOIN (SELECT question_id, COUNT(CASE correct WHEN 1 THEN 1 END) AS cnt
FROM questionnaire_answers
GROUP BY question_id) a ON q.id = a.question_id
使用子查询,如果问题没有正确答案,则返回0
试试这个:
SELECT qq.id,
COALESCE((SELECT COUNT(*)
FROM questionnaire_answers qa
WHERE qa.question_id = qq.question_id
AND qa.correct = 1), 0)
FROM questionnaire_question qq
select question_id, count(user_id)
from questionnaire_answers
where correct = 1
group by question_id
没有加入因为您已经通过包含正确的列来非规范化模式。