我有一个如下表所示的表,它是树的表示。
id --- parentid
1 NULL
2 1
3 1
4 2
这里1是根节点,4,3是叶节点,2是中间节点。如何编写打印
的SQL查询id ---- type
1 root
2 intermiditae
3 leaf
4 leaf
答案 0 :(得分:1)
这是一种方法:
SELECT mytable.id, IF(mytable.parent_id IS NULL, 'root',
IF(COUNT(children.id) > 0, 'intermediate', 'leaf'))
FROM mytable
LEFT JOIN mytable AS children ON children.parent_id = mytable.id
GROUP BY mytable.id;
" root"是parent_id
为NULL
的行。然后,计算孩子的数量足以确定该条目是否是叶子。
您还可以使用3个查询和UNION
获得相同的结果。
(SELECT mytable.id, 'root' AS type
FROM mytable
WHERE mytable.parent_id IS NULL)
UNION
(SELECT mytable.id, 'intermediate' AS type
FROM mytable
JOIN mytable AS children ON children.parent_id = mytable.id
WHERE mytable.parent_id IS NOT NULL
GROUP BY mytable.id)
UNION
(SELECT mytable.id, 'leaf' AS type
FROM mytable
LEFT JOIN mytable AS children ON children.parent_id = mytable.id
WHERE children.id IS NULL);
答案 1 :(得分:0)
使用左连接来确定子项的存在:
select id,
case when parent_id is null then 'root'
when child is null then 'leaf'
else 'intermediate' end as type
from mytable
left join (select parent_id parent, max(id) child
from mytable group by 1) x on parent = id