--------------+-------------------+
id | parent_id |
--------------+-------------------|
18 | <null> |
20 | <null> |
25 | 18 |
--------------+-------------------+
我希望我的查询选择parent_id列中不存在其id的所有ID。我该怎么做呢?
答案 0 :(得分:1)
最简单的方法是使用NOT EXISTS
返回在parent_id列中找不到的ID:
select id
from tablename t1
where not exists (select 1 from tablename t2
where t2.parent_id = t1.id)
也可以使用 NOT IN
,但要小心,必须注意NULL:
select id
from tablename
where id not in (select parent_id from tablename
where parent_id is not null)