我有一个考试数据库,有4个表:用户,答案,问题和科目。
user table
U_id | name
subjects table
S_id | Subject
questions table
Q_id | S_id | question | Correct
answers table
U_id | Q_id | answers
我需要找到每个用户每个主题的正确答案数。
我的查询
select U_id,questions.S_id ,count(Q_id)
from answers inner join questions on questions.q_id = answers.q_id
where questions.Correct = answers.answer
group by answers.U_id,questions.S_id
result:
1 | s1 | 2
1 | s2 | 3
1 | s3 | 1
2 | s1 | 1
2 | s2 | 1
给出了每个主题的正确答案数,但如果用户没有正确的答案,则不显示S_id,我需要显示0。
我需要的结果是
result:
1 | s1 | 2
1 | s2 | 3
1 | s3 | 1
2 | s1 | 1
2 | s2 | 1
2 | s3 | 0
任何帮助?
注意我使用的是MySQL,但是MS SQL服务器是很好的。
答案 0 :(得分:2)
select u.U_id, q.S_id, count(a.q_id)
from users u
cross join questions q
left join answers a on q.q_id = a.q_id and u.u_id = a.u_id and q.Correct = a.answer
group by u.U_id, q.S_id