Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从MySql表中获取所有父级和祖先级?_Php_Mysql_Sql_Recursion_Hierarchy - Fatal编程技术网

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

Php 如何从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

我正在使用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中获取任何层次结构级别的所有父/祖先

预期结果

如果我提供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
  :

你问了两个问题。你应该只问一个。对不起,现在我已经更正了帖子。