I have two database tables with a one-to-ma开发者_StackOverflowny relationship. Is it possible to select records from the 'one' table for which no records exist in the 'many' table using a single SQL statement? If so, how?
Thanks in anticipation.
Use an OUTER JOIN
:
select p.id
from parent p
left outer join child c on c.parent_id = p.id
where c.parent_id is null
select *
from table1
where not exists (select null
from table2
where MatchingColumn = Table1.MatchingColumn)
You can pull all the records from the master table that do not have any children in the "many" table like so:
SELECT T.* FROM Table1 T WHERE T.Id NOT IN(SELECT DISTINCT FKID FROM Table2)
FKID is the Foreign Key ID that links back to the master table.
精彩评论