简体   繁体   English

如何从 MySql 表中获取所有父母和祖先?

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

I'm using MySql and PHP and I have this table, where each item can contains other items and so on...我正在使用 MySql 和 PHP 并且我有这个表,其中每个项目都可以包含其他项目等等......

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

Challenge: getting all parents挑战:让所有父母

I would like a query that get all the parents/ancestors, at any hierarchy level, from a given ChildItemId.我想要一个查询,从给定的 ChildItemId 获取任何层次结构级别的所有父母/祖先。

Result expected预期结果

If I supply ChildItemId = 1如果我提供 ChildItemId = 1

AllParents
3
4
5

Any help with query, loop, CTE, php code or whatever solution?有关查询、循环、CTE、php 代码或任何解决方案的任何帮助?

In the CTE, you can get all the parents/ancestors by generating all routing table using the recursive call.在 CTE 中,您可以通过使用递归调用生成所有路由表来获取所有父母/祖先。 The following query filters by TargetItemId after generating 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

You can also filter by ChildItemId in advance.您也可以提前按 ChildItemId 进行过滤。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM