Opuesto De Una Consulta De Unión Interna


Puede alguien ayudarme a escribir sql para un scernerio como este:

Table 1

2 columns: ID, Name

Table 2

2 columns: ID, Name

Quiero una consulta para mostrar los nombres de la Tabla 1 que no están en la tabla 2. Así que filtrar todos los nombres en la tabla 1 que están en la tabla 2 es la consulta de resultados. Utilice ID para el filtrado, no nombre.

Esto me ayudará en lo que estoy tratando de hacer. Gracias de antemano

Author: Paul Sasik, 2010-10-28

5 answers

Select * from table1
left join table2 on table1.id = table2.id
where table2.id is null
 48
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-28 16:20:04

Esto debería funcionar mejor que la versión left join...is null. Ver aquí y aquí para las comparaciones.

select t1.id, t1.name
    from table1 t1
    where not exists(select null from table2 t2 where t2.id = t1.id)
 22
Author: Joe Stefanelli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-28 16:39:48

Utilice esta consulta

select
t1.*
from table1 t1
left outer join table2 t2
on t1.id=t2.id
where t2.id is null

Esto funciona uniendo todo en t1 a lo que existe en t2. la cláusula where filtra todos los registros que no existen en t2.

 16
Author: DForck42,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-10-28 16:19:52
SELECT Table1.ID, Table1.Name, Table2.ID 
FROM Table1 LEFT OUTER JOIN Table2 ON Table1.ID = Table2.ID 
WHERE Table2.ID IS NULL 

Creo que eso debería bastar.

 3
Author: Matt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-02 16:40:48
SELECT * FROM table1
WHERE table2.id NOT IN (SELECT id FROM table2)
 0
Author: Mojgan Mazouchi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-13 00:04:02