我有一个答案表,一个问题表和一个连接表。问题表有问题,答案表有这些问题的答案。问题是,这是一个多选设置。所以答案会有一些正确的答案和一些问题的错误答案。
答案是否正确用布尔值表示 - is_right。
如何在答案表中没有正确答案(同样地,答案没有错误的地方)找到哪些问题有答案?
答案 0 :(得分: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
)
如果由于某种原因想要避免使用subselect:
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
答案 1 :(得分: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。