Php 使用PostgreSQL以简单的方式获取所有父级
我有一个具有层次结构的表:Php 使用PostgreSQL以简单的方式获取所有父级,php,sql,database,postgresql,recursive-query,Php,Sql,Database,Postgresql,Recursive Query,我有一个具有层次结构的表: _________ |Plans |_____________________________________________ |-------------------------------------------------------| | id | parent | plan_name | description | |---------------------------------
_________
|Plans |_____________________________________________
|-------------------------------------------------------|
| id | parent | plan_name | description |
|-------------------------------------------------------|
| 1 0 Painting bla..bla |
| 2 1 Shopping bla..bla |
| 3 1 Scheduling bla..bla |
| 4 2 Costumes bla..bla |
| 5 2 Tools bla..bla |
| 6 2 Paints bla..bla |
|_______________________________________________________|
我想列出计划名称的所有父项,这样我就可以构建一个面包屑导航回来。使用id=6
我想得到:
Painting > Shopping > Paints
我正在将postgresql与PHP结合使用,并正在考虑一种高效的方法,尽可能简单地获取所有的父项。使用:
可以使用文本列聚合计划名称,而不是父ID的整数数组:
with recursive pl(id, parent, parents, depth) as (
select id, parent, plan_name, 0
from plans
union
select pl.id, plans.parent, plans.plan_name|| ' > ' ||pl.parents, depth+ 1
from pl
join plans on pl.parent = plans.id
)
select distinct on (id) id, parents
from pl
order by id, depth desc;
id | parents
----+--------------------------------
1 | Painting
2 | Painting > Shopping
3 | Painting > Scheduling
4 | Painting > Shopping > Costumes
5 | Painting > Shopping > Tools
6 | Painting > Shopping > Paints
(6 rows)
“Paint”是表Plans中的任务/计划名称,因此您可以调用它anyway@wingedpanther绘画是最高级的父项,然后是购物,最后的子项是绘画,所以我想列出这两个父项的名称/记录,这样我就可以用这种方式进行框架-从同一个表邻接列表中的所有内容都有点难以处理,它们创建起来很简单,但是查询起来很方便。我建议阅读,它提供了使用邻接列表结构的示例,但也强调了一个可能更好的解决方案-嵌套集模型。@wingedparter啊,是这样,我的错!谢谢,你能帮我吗?
with recursive pl(id, parent, parents, depth) as (
select id, parent, plan_name, 0
from plans
union
select pl.id, plans.parent, plans.plan_name|| ' > ' ||pl.parents, depth+ 1
from pl
join plans on pl.parent = plans.id
)
select distinct on (id) id, parents
from pl
order by id, depth desc;
id | parents
----+--------------------------------
1 | Painting
2 | Painting > Shopping
3 | Painting > Scheduling
4 | Painting > Shopping > Costumes
5 | Painting > Shopping > Tools
6 | Painting > Shopping > Paints
(6 rows)