Reputation: 64854
I have a database that contains a two tables, where these table have a relation between them, i want to retrieve records from first table that they don't have a reference in the second table ( the id's that appear in the first only) ..
what is the sql command that do that ?
Upvotes: 0
Views: 113
Reputation: 48014
SELECT FirstTable.*
FROM FirstTable
LEFT JOIN SecondTable
ON FirstTable.FirstTableId = SecondTable.FirstTableId
WHERE 1=1
AND SecondTable.SecondTableId IS NULL
Upvotes: 0
Reputation: 6832
Using JOIN
:
SELECT * FROM
table_a
LEFT JOIN table_b ON table_a.id = table_b.a_id
HAVING table_b.some_column = NULL;
Using NOT IN
:
SELECT * FROM
table_a
WHERE table_a.id NOT IN (SELECT table_b.a_id from table_b);
If you are dealing with big tables, the left join will probably be much quicker.
Upvotes: 0
Reputation: 20782
Use the NOT IN to specify that you're only interested in rows whose id has not been referenced from the other table
select * from table1 where table1.id NOT IN (select distinct referenced_id from table2)
Upvotes: 1
Reputation: 3772
Select * From Table1
Where Table1.ReferenceID NOT IN (SELECT id From Table2)
Upvotes: 2