Reputation: 30896
What's the best way to get the list of parent ID that have no child?
CREATE TABLE parent (
ID PRIMARY KEY AUTO INCREMENT
);
CREATE TABLE child (
ID PRIMARY KEY AUTO INCREMENT
ParentID INT NOT NULL
);
Upvotes: 0
Views: 102
Reputation: 344
Select Parent ID
from Parent
where ParentID NOT IN Select distinct ParentID from ChildTable
this would work :)
Upvotes: 1
Reputation: 9150
Depending on your flavour of sql:
select ID from parent minus select ParentID from child
Upvotes: 1
Reputation: 70638
This is one way:
SELECT P.ParentID
FROM dbo.Parent P
LEFT JOIN (SELECT DISTINCT ParentId FROM child) C
ON P.ParentId = C.ParentId
WHERE C.ParentID IS NULL
This is another way:
SELECT P.ParentID
FROM dbo.Parent P
WHERE NOT EXISTS (SELECT * FROM dbo.Child WHERE ParentId = P.ParentID)
Upvotes: 4
Reputation: 204756
select id from parent
where id not in (select distinct parentid from child)
Upvotes: 2