在 MySQL/MariaDB 关系 table 中获取给定父节点的所有子节点(及其子节点)
Getting all the children (and their children) of a given parent node in a MySQL/MariaDB relational table
我有一个 table 这样的:
parent, child
0 2
0 8
2 3
2 6
3 4
3 5
6 7
6 9
9 10
我正在寻找 select 给定父级的子树的查询,即如果给定的父级为“6”,则输出必须为:{10,9,7,6 }
检查这个。 @pv := '6' 中指定的值应设置为要查找其所有后代的父级的 ID。
你也可以查看直播Demo updated
select Parent, concat ( "{" ,Parent,",",GROUP_CONCAT(concat (child )SEPARATOR ','),"}") as Child
from (select * from #TableName
order by parent, child) s,
(select @pv := '6') initialisation
where find_in_set(parent, @pv) > 0
and @pv := concat(@pv, ',', child);
Output : {6,7,9,10}
要将带有父项的子项显示在一列中,请使用以下查询:
select parent as child from tchilds where parent = @pv2
union
select Child
from (select * from tchilds
order by parent, child) s,
(select @pv2 := '6') initialisation
where find_in_set(parent, @pv2) > 0
and @pv2 := concat(@pv2,',', child)
Output
如果您还有任何问题或疑虑,请告诉我们。
我有一个 table 这样的:
parent, child
0 2
0 8
2 3
2 6
3 4
3 5
6 7
6 9
9 10
我正在寻找 select 给定父级的子树的查询,即如果给定的父级为“6”,则输出必须为:{10,9,7,6 }
检查这个。 @pv := '6' 中指定的值应设置为要查找其所有后代的父级的 ID。
你也可以查看直播Demo updated
select Parent, concat ( "{" ,Parent,",",GROUP_CONCAT(concat (child )SEPARATOR ','),"}") as Child
from (select * from #TableName
order by parent, child) s,
(select @pv := '6') initialisation
where find_in_set(parent, @pv) > 0
and @pv := concat(@pv, ',', child);
Output : {6,7,9,10}
要将带有父项的子项显示在一列中,请使用以下查询:
select parent as child from tchilds where parent = @pv2
union
select Child
from (select * from tchilds
order by parent, child) s,
(select @pv2 := '6') initialisation
where find_in_set(parent, @pv2) > 0
and @pv2 := concat(@pv2,',', child)
Output
如果您还有任何问题或疑虑,请告诉我们。