简体   繁体   中英

How to use an SQL JOIN

Table A 
(id, name)
1  | alice
2  | bob

Table B
(a_id, last_name)
1    | in wonderland

I want to know the SQL query (using joins) to get the result of "items in A that are not connected to B"

a.2|a.bob

A left outer join will join two tables and return nulls for the second table in the JOIN if there is not a row that matches the join condition. After that you just specify a filter in your WHERE clause indicating that you want only records where the joined table records are null.

SELECT A.id
FROM A
LEFT JOIN B
    ON B.a_id = A.id
WHERE B.a_id IS NULL
select a.name, b.last_name
from a left outer join b on a.id = b.a_id
where b.a_id is null

您也可以使用NOT EXISTS

SELECT A.id,A.name FROM A WHERE NOT EXISTS (SELECT 1 FROM B WHERE a_id=A.id)

我不会加入这里:

SELECT id, name FROM A WHERE id not in (SELECT a_id FROM b)
SELECT id, name 
  FROM Table_A 
EXCEPT 
SELECT id, name 
  FROM Table_A 
       INNER JOIN Table_B    
          ON id = a_id;

It appears from the accepted answer that the projection of name isn't required, therefore the above may be simplified:

SELECT id
  FROM Table_A 
EXCEPT 
SELECT id
  FROM Table_B;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM