给定一个表 tree,id 是树节点的编号, p_id 是它父节点的 id 。
±—±-----+
| id | p_id |
±—±-----+
| 1 | null |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
±—±-----+
树中每个节点属于以下三种类型之一:
叶子:如果这个节点没有任何孩子节点。
根:如果这个节点是整棵树的根,即没有父节点。
内部节点:如果这个节点既不是叶子节点也不是根节点。
写一个查询语句,输出所有节点的编号和节点的类型,并将结果按照节点编号排序。上面样例的结果为:
±—±-----+
| id | Type |
±—±-----+
| 1 | Root |
| 2 | Inner|
| 3 | Leaf |
| 4 | Leaf |
| 5 | Leaf |
±—±-----+
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/tree-node
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题有一个错误点如下
select id,case when p_id=null then ‘Root’
when id not in(select p_id from tree) ‘Leaf’
else ‘Inner’ end as Type
from tree
这样查询的结果就是 本来是显示Leaf全部变成了Inner
因为在SQL语法中 A not in B(其中包括null) 作比较 则结果就是false 那么语句直接跳到else 输出的就是Inner
相当于 A!=NULL select if(1 = null, ‘true’, ‘false’) 任何与null值的对比都将返回null
正确写法
select id,case when p_id=null then ‘Root’
when id in (select p_id from tree) ‘Inner’
else ‘Leaf’ end as Type
from tree