选择MariaDB / MySql中任何一个未答复的多项选择题

时间:2016-06-20 17:02:58

标签: mysql sql

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);

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()结构也适用。