Reputation: 8824
Lets say I have table A
, with an id
column, and table B with an A_id
column. A_id
is a foreign key of id
. Now, if I want to get all id's from A of which B has a foreign key link, I can do
SELECT id FROM A JOIN B ON id = A_id
However, how can I select all id's from A where B does not link to? (without selecting all id's and subtracting the above subset from that)
Upvotes: 4
Views: 1001
Reputation: 44343
SELECT A.id FROM
A LEFT JOIN B ON A.id = B.A_id
WHERE B.A_id IS NULL;
Upvotes: 2
Reputation: 425431
SELECT id
FROM a
WHERE id NOT IN
(
SELECT a_id
FROM b
)
This will use an anti-join: for each record from a
, it will search b
for the record's id
(using an index on b.a_id
) and if none found, return the record.
Upvotes: 3