【问题标题】:Getting all descendants for a given element in MySQL获取MySQL中给定元素的所有后代
【发布时间】:2016-12-18 06:18:28
【问题描述】:

我有一个相当简单的自引用表,如下所示:

表 1

id      parent_id
1       NULL
2       1
3       NULL
4       1
5       2
6       5
7       2
8       4

我需要生成一个新表,其中每个元素的所有后代都关联。看这个例子:

表 2

element  descendants
1        2
1        5
1        6
1        7
1        4
1        8
2        5
2        6
2        7
5        6
4        8

请注意,3 不存在,因为它没有任何子级。

如何使用存储过程来实现这一点?我可以获得直接的父子关系,但我很难获得给定元素的所有后代。

(现实世界的表是 ~15k 行和 ~7 级层次结构,但它的级别不是预定义的,所以假设是 N)

【问题讨论】:

标签: mysql sql stored-procedures hierarchical-data


【解决方案1】:

这可以通过递归 CTE 来完成。 MySQL 现在支持递归 CTE,如 MySQL Server Blog 中所述。

假设一个名为“self_ref”的表,递归 CTE 将类似于:

with recursive ref(element, descendant) as (
select parent_id, id from self_ref
union 
select element, id
from ref as r
    inner join self_ref as s on s.parent_id = r.descendant
where parent_id is not null
)
select element, descendant from ref
where element is not null
order by element, descendant;

(这是为 Postgres 编写的,但 MySQL 语法如果不相同,则类似。)

【讨论】:

  • 这是 MySQL 8 中的新功能吗?我正在使用 5.7
  • 是的。如果您无法升级,请考虑将数据复制到支持递归 CTE 的 DBMS,在那里完成工作,然后将数据复制回 MySQL。本地安装 Postgres 可以为您服务。
猜你喜欢
  • 2012-07-31
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
相关资源
最近更新 更多