Getting all the children (and their children) of a given parent node in a MySQL/MariaDB relational table(在 MySQL/MariaDB 关系表中获取给定父节点的所有子节点(及其子节点))
问题描述
我有一张这样的桌子:
父、子0 20 82 32 63 43 56 76 99 10我正在寻找一个查询来选择给定父级的子树,即如果给定父级是6",则输出必须是:{10,9,7,6}
看看这个.@pv := '6' 中指定的值应设置为要查找其所有后代的父级的 id.
您也可以查看实时
如果您仍有任何问题或疑虑,请告诉我们.
I have a table like this:
parent, child
0 2
0 8
2 3
2 6
3 4
3 5
6 7
6 9
9 10
I'm looking for a query to select the sub-tree of a given parent, i.e. If the given parent is "6", the output must be: {10,9,7,6}
Chek this. The value which specified in @pv := '6' should be set to the id of the parent that you want to find all the descendants of it.
also you can check live 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}
For display childs with parent into one column use below query :
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
let us know if you have still any questions or concerns.
这篇关于在 MySQL/MariaDB 关系表中获取给定父节点的所有子节点(及其子节点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 MySQL/MariaDB 关系表中获取给定父节点的所有子节点(及其子节点)
基础教程推荐
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
