从一个表中获取记录,而另一个表中没有记录

时间:2009-12-31 03:22:30

标签: sql mysql database

SURVEYS表:

SurveyID
UserID
Question
Choice1
Choice2
Choice3

RESPONSES表:

UserID
SurveyID
Answer

第一个愿望(已实现):向我展示用户28已启动的所有调查:

SELECT * 
  FROM Surveys 
 WHERE Surveys.UserID = 28

第二个愿望(已实现):向我展示用户28已回答的所有调查:

SELECT * 
  FROM Surveys 
INNER JOIN Responses ON Surveys.SurveyID = Responses.SurveyID 
 WHERE Responses.UserID = 28

第三个愿望(未实现):

显示所有未由用户28发起的调查以及哪些用户28尚未回答... SELECT * FROM调查INNER JOIN响应ON Surveys.SurveyID = Responses.SurveyID WHERE Surveys.UserID<> 28 AND Responses.UserID<> 28 [或者:在哪里没有Surveys.UserID = 28 OR Responses.UserID = 28]

第三个查询会删除用户28的记录,但会显示同一调查的其他实例。例如,假设用户29回答了调查问卷。将返回一行,因为WHERE不会禁止用户29的记录。

我想过使用子查询 - 类似于:SELECT * FROM Surveys WHERE Surveys.UserID<> 28 AND Surveys.SurveyID<> (SELECT Responses.SurveyID WHERE Responses.UserID = 28) - 但这不起作用,因为子查询可以轻松生成多行。

解决方案是什么?

2 个答案:

答案 0 :(得分:6)

使用NOT IN:

SELECT s.*
  FROM SURVEYS s
 WHERE s.userid != 28
   AND s.surveyid NOT IN (SELECT r.survey_id
                            FROM RESPONSES r
                           WHERE r.userid = 28)

使用LEFT JOIN / IS NULL:

   SELECT s.*
     FROM SURVEYS s
LEFT JOIN RESPONSES r ON r.survey_id = s.surveyid
                     AND r.user_id = 28
    WHERE s.userid != 28
      AND r.userid IS NULL

使用NOT EXISTS:

SELECT s.*
  FROM SURVEYS s
 WHERE s.userid != 28
   AND NOT EXISTS (SELECT NULL
                     FROM RESPONSES r
                    WHERE r.userid = 28
                      AND r.survey_id = s.surveyid)

在列出的选项中,NOT INLEFT JOIN/IS NULL是等效的,但我更喜欢NOT IN,因为它更具可读性。

答案 1 :(得分:0)

我觉得应该这样吗?

SELECT * 
FROM Surveys s
WHERE s.UserID != 28 
AND s.SurveyID NOT IN (SELECT R.SurveyID FROM Responses R WHERE R.UserID = 28)