我有下表taxonomy
,如下所示:
taxonomy_id | parent_id
------------------------
1 | 0
2 | 0
3 | 1
4 | 1
5 | 2
6 | 3
我想选择所有不是父母的物品,在4,5和6的情况下。前3项显然是父母,我不需要它们。应该是什么查询
答案 0 :(得分:3)
使用NOT EXISTS
SELECT taxonomy_id, parent_id
FROM dbo.Taxonomy t1
WHERE NOT EXISTS(
SELECT 1 FROM dbo.Taxonomy t2
WHERE t1.taxonomy_id=t2.parent_id
)
至少在SQL-Server中,这是最好的方法: Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
答案 1 :(得分:0)
试试这个
SELECT * FROM taxonomy WHERE taxonomy_id NOT IN (SELECT parent_id FROM taxonomy WHERE parent_id <> 0)
答案 2 :(得分:0)
select taxonomy_id
from taxonomy
where taxonomy_id not in
(
select distinct parent_id from taxonomy
)
答案 3 :(得分:0)
在MySQL中,你需要求助于相关的子查询。
要么不存在:
select t.*
from taxonomy t
where t.parent_id <> 0
and not exists (select 1 from taxonomy t2 where t2.parent_id <> t.taxonomy_id)
或不在:
select t.*
from taxonomy t
where t.parent_id <> 0
and t.taxonomy_id not in (select t2.parent_id from taxonomy t2)
答案 4 :(得分:0)
可替换地:
select * from taxonomy where taxonomy_id <> all (select parent_id from taxonomy)
感谢用户Tim Schmelter优质服务sqlfiddle.com
的链接