SQL Fiddle(小提琴并不是真的对我有用)
我想要获取身份为99
的用户尚未接听的任何一个多项选择问题。他只回答了一个问题 - A question
到目前为止user_answer
表中显示的是choice id
而不是question_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);
答案 0 :(得分: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
。由于他们对{{1}}值的处理方式不同,我强烈建议您使用NULL
- NOT EXISTS
值的处理更为直观。
然后,您可以在查询中使用它来获取有关未答复问题的其他信息:
NULL
如果您愿意,可以通过删除子查询来解决如何“简化”此查询的问题。
答案 1 :(得分:1)
SELECT
*
FROM
(
SELECT DISTINCT
q.question_id
,q.question
FROM
question_choice qc
INNER JOIN question q
ON q.question_id = qc.question_id
LEFT JOIN user_answer ua
ON qc.choice_id = ua.choice_id
AND ua.user_id = 99
WHERE
ua.user_id IS NULL
LIMIT 1
) nq
INNER JOIN question_choice nqc
ON nq.question_id = nqc.question_id
我喜欢LEFT JOIN
模型,但NOT EXISTS()
结构也适用。