如何在单表mysql中选择叶子的根
我有一张这样的桌子如何在单表mysql中选择叶子的根,mysql,root,parent,Mysql,Root,Parent,我有一张这样的桌子 id , parent_id , name , leaf 1 , 0 ,parent 1 , 0 2 , 0 ,parent 2 , 0 3 , 1 ,child 1 , 0 4 , 3 ,child 2 , 1 5 , 2 ,child 3 , 0 6 , 5 ,child 4 , 1 7 ,
id , parent_id , name , leaf
1 , 0 ,parent 1 , 0
2 , 0 ,parent 2 , 0
3 , 1 ,child 1 , 0
4 , 3 ,child 2 , 1
5 , 2 ,child 3 , 0
6 , 5 ,child 4 , 1
7 , 0 ,child 5 , 1
我要选择叶子,它的根名不是父名
像下面这样
id , name , root_name
4 , child 2 , parent 1
6 , child 4 , parent 2
7 , child 5 , null
三个可能有很多层次
我如何在MySQL和存储过程中做到这一点 在我看来,您应该有两个表来处理这个问题。一个用于节点,一个用于节点关系。然后你可以做一个连接,得到你想要的结果 阅读相关内容以及它的重要性,您可以在第三个范式之前规范化您的DB
nodes (
id,
name
)
node_to_parent (
id
node_id,
parent_id
)
然后您可以这样查询:
Select n.name, np.parent_id from nodes
join node_to_parent np
on np.node_id = n.node_id;
您可以执行以下操作以获得所需的输出
select t.id, t.name, m.root_name from (select id,parent_id,name,leaf from urtable where leaf=1) t
join urtable m on (t.parent_id=m.parent_id and t.id=m.id)
您会发现MySQL目前不支持递归。选择包括编写存储过程、处理应用程序代码中的逻辑、尽可能频繁地将表连接到自身,或者切换到替代模型,例如嵌套集。所有这些话题在其他地方都有广泛的讨论,所以我不在这里详细阐述。谢谢您的回复。如何使用存储过程仅选择叶子的根节点?