我不完全清楚你为什么不将 5 包含在输出中的意思,但这会给你结果:
select id from mytable where id in (2,4,5,6) and parentid not in (2,4,5,6)
要在排除值方面再上一层,您必须将表连接到自身。像这样的:
select id from mytable join mytable parenttab on mytable.parentid = parenttab.id
where mytable.id in (2,4,5,6) and
mytable.parentid not in (2,4,5,6) and
parenttab.parentid not in (2,4,5,6)
如果您想进入任何层次结构,您需要使用recursive CTE。像这样的:
WITH RecursiveParentList ( parentid )
AS
(
SELECT parentid from Mytable
where id in (2,4,5,6)
UNION ALL
SELECT ParentTable.id
FROM Mytable AS ParentTable
INNER JOIN RecursiveParentList AS ChildTable
ON ParentTable.id = ChildTable.parentid
)
SELECT MyTable.id
FROM MyTable
LEFT JOIN RecursiveParentList on MyTable.id = RecursiveParentList.id
WHERE RecursiveParentList.id is null;
注意 1:您需要对此进行调试。我把它从我的头顶上拉下来,不会测试它。
注意 2:我只会将 IN 子句用于像这样的简短列表。如果您的排除项目列表变长或从另一个表中提取,您将需要使用另一个 CTE 将该列表定义为它自己的表并将您的第一个查询加入到它。