Mysql
 sql >> Database >  >> RDS >> Mysql

Recupera i record da una tabella in cui non c'è un record in un'altra

Utilizzo di 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)

Utilizzando 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

Utilizzo di 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)

Tra le opzioni elencate, il NOT IN e LEFT JOIN/IS NULL sono equivalenti anche se preferisco NOT IN perché è più leggibile.