2016-09-17 45 views
0

我有一张如下所示的表格,它是树的表示。MySQL病例声明问题

id --- parentid 
1  NULL 
2  1 
3  1 
4  2 

这里1是根节点,4,3是叶节点,2是中间节点。如何写它打印

id ---- type 
1  root 
2  intermiditae 
3  leaf 
4  leaf 
+0

我会为根添加'ID = 1的parentId = 1'到数据。查询应该与3个选择的联合,根,interm和leaf:'select id,'root'作为id = parentid union select ...的数据类型。处理这个问题并返回查询。 – PeterMmm

+0

是的,对不起,我会编辑 – Vinny

回答

1

这里是做的一种方式的SQL查询:

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; 

“根”是其parent_idNULL行。然后,计算孩子的数量就足以确定入口是否是叶子。


您还可以获取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); 
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