如何从 MySql table 获取所有 parents 和祖先?

How to get all parents and ancestors from a MySql table?

我正在使用 MySql 和 PHP 我有这个 table,其中每个项目可以包含其他项目等等...

MyTable

RowId | ItemId | ChildItemId
1     | 1      | NULL
2     | 2      | NULL
3     | 3      | 1
4     | 4      | 1
5     | 4      | 2
6     | 5      | 3
7     | 5      | 4

挑战:获得全部parents

我想要一个从给定的 ChildItemId 获取任何层次结构级别的所有 parents/ancestors 的查询。

预期结果

如果我提供 ChildItemId = 1

AllParents
3
4
5

对查询、循环、CTE、php 代码或任何解决方案有任何帮助吗?

在CTE中,可以通过递归调用生成所有路由table得到所有parents/ancestors。 以下查询在生成 table.

后按 TargetItemId 过滤
with recursive Ancesters as (
  select 1 as Level, ChildItemId as TargetItemId, RowId, ItemId as AncesterId, ChildItemId
  from MyTable
  where ChildItemId is not null
  union all
  select a.Level+1, a.TargetItemId, m.RowId, m.ItemId, m.ChildItemId
  from MyTable m inner join Ancesters a
  on m.ChildItemId = a.AncesterId
)
select distinct AncesterId from Ancesters where TargetItemId=1

您也可以提前通过ChildItemId进行筛选。

with recursive Ancesters as (
  select 1 as Level, ChildItemId as TargetItemId, RowId, ItemId as AncesterId, ChildItemId
  from MyTable
  where ChildItemId=1
  :