使用 PostgreSQL 以简单的方式获取所有 parents

Fetching all parents in simple way with PostgreSQL

我有一个具有层次结构的 table:

    _________
    |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            | 
    |_______________________________________________________|

我想列出计划名称 Paints 的所有 parents,这样我就可以建立一个面包屑导航返回。使用 id = 6 我喜欢得到:

Painting > Shopping > Paints

我将 postgresql 与 PHP 一起使用,并正在考虑尽可能简单地获取所有 parents 的有效方法。

使用recursive with query:

with recursive pl(id, parent, parents) as (
    select id, parent, array[parent]
    from plans
union
    select pl.id, plans.parent, pl.parents|| plans.parent
    from pl
    join plans on pl.parent = plans.id
    )
select distinct on (id) id, parents
from pl
order by id, array_length(parents, 1) desc

 id | parents
----+---------
  1 | {0}
  2 | {1,0}
  3 | {1,0}
  4 | {2,1,0}
  5 | {2,1,0}
  6 | {2,1,0}
(6 rows)

SqlFiddle

您可以使用文本列来聚合计划名称,而不是 parent 个 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)