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) - 但这不起作用,因为子查询可以轻松生成多行。
解决方案是什么?
答案 0 :(得分:6)
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)
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
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 IN
和LEFT 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)