Php 如何从MySql表中获取所有父级和祖先级?
我正在使用MySql和PHP,我有一个表,其中每个项目可以包含其他项目,等等 MyTablePhp 如何从MySql表中获取所有父级和祖先级?,php,mysql,sql,recursion,hierarchy,Php,Mysql,Sql,Recursion,Hierarchy,我正在使用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 挑战:让所有家长参与 我想要一个查询,从给定的ChildItemId
RowId | ItemId | ChildItemId
1 | 1 | NULL
2 | 2 | NULL
3 | 3 | 1
4 | 4 | 1
5 | 4 | 2
6 | 5 | 3
7 | 5 | 4
挑战:让所有家长参与
我想要一个查询,从给定的ChildItemId中获取任何层次结构级别的所有父/祖先
预期结果
如果我提供ChildItemId=1
AllParents
3
4
5
关于查询、循环、CTE、php代码或任何解决方案的任何帮助?在CTE中,您可以通过使用递归调用生成所有路由表来获得所有父级/祖先级。 以下查询在生成表后按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
:
你问了两个问题。你应该只问一个。对不起,现在我已经更正了帖子。