[英]Finding "Leaf" in a Tree using MySQL
我正在嘗試識別樹中的“葉子”,但我很困惑為什么我的查詢沒有給我想要的東西。
這是問題所在:
所以我的想法是,只要 id 不在 p_id 列中,那么它就應該是“葉子”
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 。
select distinct a_id, status from( select a.id as a_id,a.pid as a_pid, b.id as b_id, b.pid as b_pid, case when b.id is not null and a.pid is not null then 'Inner ' 當 b.id 為 null 時為 'leaf' 當 a.pid 為 null 時為 'root' 否則 null 結束為 'status'
從葉子 a 左加入葉子 b on a.id = b.pid)temp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.