SQL Fiddle(小提琴对我不起作用)
我想获取id为99
的用户尚未回答的任何一个多项选择题。他只回答了一个问题-A question
见存储user_answer
而不是问题id的choice id
表。
我的预期结果应该是这样的:
Question Question_id Choice_id Choice
B question 2 3 B choice 1
B question 2 4 B choice 2
或者
C question 3 5 C choice 1
C question 3 6 C choice 2
C question 3 7 C choice 3
使用下面的Sql,我在获取B或C问题及其选择时遇到困难
SELECT q.question_id,q.question,qc.choice,qc.choice_id
FROM question_choice qc
INNER JOIN question q ON q.question_id = qc.question_id
WHERE qc.question_id NOT IN
(SELECT question_id
FROM user_answer ua
INNER JOIN question_choice qc ON qc.choice_id = ua.choice_id
WHERE ua.user_id = 99)
GROUP BY qc.choice_id
ORDER BY q.question_id;
我不知道该在
limit clause
中放些什么,以便只获取一个带有可变选择数的未回答问题。表格:
CREATE TABLE question
(question_id INT, question VARCHAR(100));
CREATE TABLE question_choice
(question_id INT, choice_id INT,choice VARCHAR(100));
CREATE TABLE user_answer
(user_id INT,choice_id INT);
INSERT INTO question (question_id,question)
VALUES
(1,"A question"),
(2,"B question"),
(3,"C question");
INSERT INTO question_choice (choice_id,choice,question_id)
VALUES
(1,"A choice 1",1),
(2,"A choice 2",1),
(3,"B choice 1",2),
(4,"B choice 2",2),
(5,"C choice 1",3),
(6,"C choice 2",3),
(7,"C choice 3",3);
INSERT INTO user_answer(user_id,choice_id)
VALUES
(99,2);
最佳答案
你在正确的轨道上。但这可能有助于你考虑达成解决方案。
首先,可以使用以下查询获取未回答的问题列表:
SELECT q.*
FROM question q
WHERE NOT EXISTS (SELECT question_id
FROM user_answer ua INNER JOIN
question_choice qc
ON qc.choice_id = ua.choice_id
WHERE ua.user_id = 99 AND qc.question_id = q.question_id
);
注意,我用
NOT IN
替换了NOT EXISTS
。因为它们对NULL
值的处理方式不同,我强烈建议使用NOT EXISTS
——对NULL
值的处理更直观。然后,您可以在查询中使用它来获取有关未回答问题的其他信息:
SELECT q.question_id, q.question, qc.choice, qc.choice_id
FROM (SELECT q.*
FROM question q
WHERE NOT EXISTS (SELECT question_id
FROM user_answer ua INNER JOIN
question_choice qc
ON qc.choice_id = ua.choice_id
WHERE ua.user_id = 99 AND qc.question_id = q.question_id
)
) q JOIN
question_choice qc
ON qc.question_id = q.question_id;
如果愿意,可以通过删除子查询来研究如何“简化”此查询。