Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

MySQL - Selecionar tudo, exceto o que está nesta tabela

Usando LEFT JOIN/IS NULL

   SELECT DISTINCT
          i.data
     FROM IMAGE i
     JOIN USER_IMAGE ui ON ui.image_id = i.id
LEFT JOIN USER u ON u.id = ui.user_id
                AND u.user = ?
    WHERE u.id IS NULL

Usando NOT IN

SELECT DISTINCT
       i.data
  FROM IMAGE i
  JOIN USER_IMAGE ui ON ui.image_id = i.id
 WHERE ui.user_id NOT IN (SELECT u.id
                            FROM USER u
                           WHERE u.user = ?)

Usando NOT EXISTS

SELECT DISTINCT
       i.data
  FROM IMAGE i
  JOIN USER_IMAGE ui ON ui.image_id = i.id
 WHERE NOT EXISTS(SELECT NULL
                    FROM USER u
                   WHERE u.id = ui.user_id
                     AND u.user = ?)

Desempenho:


O LEFT JOIN/IS NULL e NOT IN fornecer desempenho equivalente - o NOT EXISTS é ~30% menos eficiente. Veja mais detalhes .