我有一张这样的桌子:
parent, child
0 2
0 8
2 3
2 6
3 4
3 5
6 7
6 9
9 10我正在寻找一个查询来选择给定父级的子树,也就是说,如果给定的父级是"6",则输出必须是:{10,9,7,6}
发布于 2016-12-13 05:17:16
切克这个。在@pv := '6‘中指定的值应该设置为要查找它的所有后代的父父的id。
此外,您还可以查看实时演示更新。
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);产出:{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)输出

如果您还有任何问题或关切,请告诉我们。
https://stackoverflow.com/questions/41113828
复制相似问题