0

我有一个答案表、一个问题表和一个连接表来加入它们。问题表有问题,答案表有这些问题的答案。问题是,这是一个多选设置。因此,对于某个问题,答案将有一些正确答案和一些错误答案。

答案是否正确由布尔值 - is_right 指示。

如何在答案表中找到没有正确答案的问题(同样,没有错误答案的问题)?

4

2 回答 2

1
SELECT *
FROM questions
WHERE EXISTS (
  SELECT TRUE
  FROM answers a1
  WHERE a1.question_id = questions.question_id
  AND a1.is_right
)
AND NOT EXISTS (
  SELECT TRUE
  FROM answers a2
  WHERE a2.question_id = questions.question_id
  AND !a2.is_right
)

如果出于某种原因要避免子选择:

SELECT question_id,
       SUM(is_right) AS right_answers,
       SUM(!is_right) AS wrong_answers
FROM questions
JOIN answers ON answers.question_id = questions.question_id
GROUP BY question_id
HAVING right_answers > 0
AND wrong_answers = 0
于 2012-09-23T12:58:52.697 回答
0

我不知道你为什么有一个连接表,因为答案只有一个问题。

在没有连接表的情况下,查询没有正确答案的问题:

SELECT questions.*
FROM questions LEFT OUTER JOIN answers
  ON questions.id = answer.question_id AND answer.is_right = false
WHERE answer.id IS NULL

使用名为 answers_questions 的连接表,SQL 将是:

SELECT questions.*
FROM questions
  LEFT OUTER JOIN answers_questions
    ON answers_questions.question_id = question.id
  LEFT OUTER JOIN answers
    ON answers_questions.answer_id = answer.id AND answer.is_right = false
WHERE answer.id IS NULL

这还将为您提供没有链接答案的问题。要获得没有正确答案的问题,在与答案相关的问题中,将第一个 LEFT OUTER JOIN 更改为 INNER JOIN。

于 2012-09-23T14:37:37.290 回答