【问题标题】:MySQL 5.7 recursive query on hierarchy data with unknown levelsMySQL 5.7 对具有未知级别的层次结构数据的递归查询
【发布时间】:2021-10-03 00:02:01
【问题描述】:

我正在开发一个层次结构数据结构,我想在其中执行递归以获得所需的输出

 id       role_id      reporting_to
 ------+-------------+-----------------
1          100             101
1          101             102
1          102             103
1          103             104

如果我将103 作为输入角色,我想得到以下输出

  id    role_id      reporting_to
-----------+-------------+-----------------
    1          100             101
    1          101             102
    1          102             103

输出应该是从输入到最后一个孩子。试过下面的例子,但它没有返回正确的输出

select id,role_id,reporting_to
from (select * from role_mapping order by reporting_to,id) rm_sorted,
     (select @r:='103') initialisation
where find_in_set(reporting_to, @r)
and length(@r := concat(@r, ',', role_id))

【问题讨论】:

  • 一般来说这不能作为查询来解决(或者它需要在一些数据限制,例如CHECK role_id < reporting_to约束)。使用迭代存储过程。
  • 您需要的递归深度是否有一些(小)限制?如果没有,您将需要使用存储过程(或者只是升级到 mysql 8 或 mariadb)
  • 正如其他人所提到的,5.7 中的邻接表模型自然不适合递归。考虑升级或切换到嵌套集模型。
  • 我认为只有迭代方法是可能的。谢谢大家。

标签: mysql sql mysql5


【解决方案1】:

除非你使用函数,否则mysql5.7永远不能进行递归查询。

也可以使用其他有递归的语言,如mysql5.8、oracle、java等,生成路径列,像这样(假设104为根节点)

id role_id reporting_to path
1 100 101 104/103/102/101/100
1 101 102 104/103/102/101
1 102 103 104/103/102
1 103 104 104/103

【讨论】:

    猜你喜欢
    • 2013-11-07
    • 2019-07-02
    • 1970-01-01
    • 2015-12-24
    • 2014-01-25
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多