使用 MySQL 在树中查找“叶子”

DJ-*_*ing 2 mysql sql

我试图识别树中的“叶子”,但我很困惑为什么我的查询没有给我我想要的东西。

问题是这样的:

在此输入图像描述

所以我的想法是,只要id不在p_id列中,那么它就应该是“Leaf”

select id, 'Leaf' as type
from Tree
where id not in (select distinct(p_id)
                 from Tree)
Run Code Online (Sandbox Code Playgroud)

但是,上面的查询没有给我返回任何结果。

该解决方案与我的几乎相同,只是它指定 p_id 不能为 NULL,然后它返回我想要的内容。

select id
from Tree
where id not in(select distinct(p_id) 
                from Tree 
                where p_id IS NOT NULL)
Run Code Online (Sandbox Code Playgroud)

我很困惑为什么添加 where 子句会产生影响?

sla*_*kso 5

你猜到了。这是因为 NULL 不与任何东西进行比较。值与 null 没有不同,并且值与 null 不同。

您可以通过以下查询得到结果:

select distinct t.id, 
  if (p.id is null, 'Root', if (d.id is null, 'Leaf', 'Inner'))
from Tree t
  left join Tree p on p.id=t.p_id
  left join Tree d on d.p_id=t.id;
Run Code Online (Sandbox Code Playgroud)

请参阅dbfiddle