gpt4 book ai didi

mysql - 使用 MySQL 在树中查找 "Leaf"

转载 作者:行者123 更新时间:2023-12-02 18:16:13 26 4
gpt4 key购买 nike

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

问题是这样的:

enter image description here

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

select id, 'Leaf' as type
from Tree
where id not in (select distinct(p_id)
from Tree)

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

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

select id
from Tree
where id not in(select distinct(p_id)
from Tree
where p_id IS NOT NULL)

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

最佳答案

你猜对了。这是因为 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;

参见dbfiddle .

关于mysql - 使用 MySQL 在树中查找 "Leaf",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71551483/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com