获取没有孩子的父ID列表的最佳方法是什么?
CREATE TABLE parent (
ID PRIMARY KEY AUTO INCREMENT
);
CREATE TABLE child (
ID PRIMARY KEY AUTO INCREMENT
ParentID INT NOT NULL
);
答案 0 :(得分:4)
这是一种方式:
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
这是另一种方式:
SELECT P.ParentID
FROM dbo.Parent P
WHERE NOT EXISTS (SELECT * FROM dbo.Child WHERE ParentId = P.ParentID)
答案 1 :(得分:2)
select id from parent
where id not in (select distinct parentid from child)
答案 2 :(得分:1)
取决于你的sql风格:
select ID from parent minus select ParentID from child
答案 3 :(得分:1)
Select Parent ID
from Parent
where ParentID NOT IN Select distinct ParentID from ChildTable
这样可行:)