Fetch records from one table where there's not a record in another

后端 未结 2 1882
感动是毒
感动是毒 2021-01-22 08:57

SURVEYS table:

SurveyID
UserID
Question
Choice1
Choice2
Choice3

RESPONSES table:

UserID
SurveyID
         


        
相关标签:
2条回答
  • 2021-01-22 09:12

    Something like this I think should do?

    SELECT * 
    FROM Surveys s
    WHERE s.UserID != 28 
    AND s.SurveyID NOT IN (SELECT R.SurveyID FROM Responses R WHERE R.UserID = 28)
    
    0 讨论(0)
  • 2021-01-22 09:31

    Using 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)
    

    Using 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
    

    Using 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)
    

    Of the options listed, the NOT IN and LEFT JOIN/IS NULL are equivalent though I prefer the NOT IN because it is more readable.

    0 讨论(0)
提交回复
热议问题