【问题标题】:Getting all the children (and their children) of a given parent node in a MySQL/MariaDB relational table在 MySQL/MariaDB 关系表中获取给定父节点的所有子节点(及其子节点)
【发布时间】:2016-12-13 04:38:41
【问题描述】:

我有一张这样的桌子:

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}

【问题讨论】:

  • MySQL 不支持递归查询,理想情况下您可以使用递归查询来解决此类问题。树可以有多深,最大深度是固定的吗?
  • 它不是深度固定的,但我认为不超过 6 级深度。很遗憾听到 MySQL 不支持递归查询 D:!
  • 如果您可以接受,您可以进行 5 次自我加入。
  • 当然,来自 PHP 的递归查询是没有问题的。使用固定的最大长度,您也可以在列中执行此操作。
  • 考虑使用 MariaDB 10.2 或 MySQL 8.0.x 的 CTE

标签: mysql sql database tree mariadb


【解决方案1】:

看看这个。 @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);

输出:{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)

输出

如果您仍有任何问题或疑虑,请告诉我们。

【讨论】:

  • TQ DBA @BerndBuffen
  • 谢谢,我对你的答案投了赞成票,但我真的不需要一个连续输出,只有一列输出那个数字,你能编辑你的答案,所以我可以在 phpmyadmin 上测试。跨度>
  • @Mr.Bhosale 可以吗?
  • @alessadro 回答已更新,并检查所有查询的更新演示链接。仍有任何问题与我联系 sujayb7@gmail
  • 非常感谢您的专业反馈;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多