开发者

Testing for the absence of child records in MySQL

开发者 https://www.devze.com 2023-02-17 09:05 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消