查询以确定未使用的值

时间:2018-02-26 19:20:48

标签: sql sql-server

我有两个查询从各种表中获取数据。查询#1返回包含2个特定问题的所有答案的数据。查询#2返回所有可能的答案(定义的列表)。

Table Client_Answers ca
QuestionID      AnswerID
1               1
2               3
2               3
2               2
1               2

Table Questions q
QuestionID      QuestionID
1               question #1
2               question #2
3               question #3
4               question #4

Table Answers a
AnswerID        Answer
1               answer abc
2               answer xyz
3               answer 123
4               answer 456
5               answer cba

我只关心问题#1& #2并可以从Table Client_Answers中查询它们(问题/答案)。现在我需要知道哪些问题可用于问题#1和#2从未使用过! 我尝试使用NOT EXISTS如下,但它没有返回任何数据。

--Query #1
SELECT q.question
,a.Answer
FROM Client_Answers ca
INNER JOIN Questions q ON q.ID = ca.QuestionID
INNER JOIN Answers a ON a.ID = ca.AnswerID
WHERE ca.ID IN ('1','2')
AND NOT EXISTS
( --Query #2 possible answers
  SELECT 1
FROM Answers a
INNER JOIN Question q ON q.ID = a.QuestionID
WHERE q.ID IN ('1','2')
)

我希望查询返回

answer 456
answer cba

我做得不好?不确定我是否应该使用EXCEPT语句,但不知道如何使用它。这是在SQL Server 2008上运行的。谢谢。

2 个答案:

答案 0 :(得分:2)

这个怎么样

SELECT a.answer
FROM answers AS a
WHERE a.answerID NOT IN 
(
    SELECT DISTINCT ca.answerID
    FROM questions AS q
         inner join
         client_answers AS ca ON ca.questionID=q.questionID
    WHERE questionID in (1,2)
)

答案 1 :(得分:1)

在最简单的形式中,如果您的答案独立于问题(即,任何问题可以有任何可用的答案,他们并不限制每个问题),未使用的答案可以如下:

SELECT * FROM Answers
WHERE AnswerId NOT IN (SELECT AnswerId FROM Client_Answers WHERE QuestionId IN (1, 2))

如果您需要针对每个问题提供这些答案,请执行

SELECT * FROM Answers a, Question q
WHERE AnswerId NOT IN (
    SELECT AnswerId FROM Client_Answers ca WHERE ca.QuestionId = q.QuestionId)
AND QuestionId IN (1,2)

请注意笛卡尔积(在这种情况下可能会很慢)。您还可以获得更多结果,例如答案1并未用于问题2