我有一张桌子有问题,另一张桌子有正确答案 如果有任何用户尝试提问,那么我需要带分数的结果。
create table questions (question_id int, question_title varchar(50), marks int);
insert into questions values
(1, 'Question 1', 5),
(2, 'Question 2', 5);
create table answers (answer_id int, question_id int, is_true int, answer_title varchar(50));
insert into answers values
(1,1,0,'a'),
(2,1,1,'b'),
(3,2,1,'p'),
(4,2,1,'q');
create table user_quiz_attempt (attempt_id int, question_id int, answer_id int, user_id int);
insert into user_quiz_attempt values
(1,1,2,12),
(2,2,3,12),
(3,1,2,13),
(4,2,3,13),
(5,2,4,13);
我想要结果:-
我的查询:-
select
sum(questions.marks)
from
questions
inner join answers
on questions.question_id = answers.question_id
inner join user_quiz_attempt
on answers.answer_id = user_quiz_attempt.answer_id
where
answers.is_true = 1
and user_quiz_attempt.user_id = 12/13
答案 0 :(得分:0)
这是我的尝试:
http://sqlfiddle.com/#!9/e07258/2
SELECT
user_quiz_attempt.user_id,
SUM(questions.marks)
FROM user_quiz_attempt
INNER JOIN answers
ON answers.answer_id = user_quiz_attempt.answer_id
AND answers.is_true = 1
INNER JOIN questions
ON questions.question_id = answers.question_id
WHERE user_quiz_attempt.user_id IN (12,13)
GROUP BY user_quiz_attempt.user_id;
预期结果与当前结果的问题只是您的数据:
(1,1,0,'a'),
(2,1,1,'b'),
(3,2,1,'p'), <--
(4,2,1,'q'); <--
因此,Qustion 2
的两个答案都是is_true
。如果将(3,2,1,'p')
更改为(3,2,0,'p')
,将获得预期的结果。