从Postgresql中的给定子项获取父级的整个层次结构

ran*_*may 6 sql postgresql

以下是我正在查看的数据示例:

表:

id     |    name    |   parent_id
_______|____________|______________
1      |Root        | null
2      |Parent #2   | 1
3      |Parent #3   | 1
4      |Parent #4   | 2
5      |Child #5    | 2
6      |Child #6    | 2
7      |Child #7    | 3
8      |Child #8    | 3
9      |Child #9    | 3
Run Code Online (Sandbox Code Playgroud)

使用递归查询,我可以从Parent开始,并获取所有关联的子项.

我的问题是,如何从孩子开始,让所有相关的父母,祖父母等等,直到根.

所以,鉴于Child#9,我想要一个返回以下内容的查询:

id     |    name    |   parent_id
_______|____________|______________
1      |Root        | 0
3      |Parent #3   | 1
9      |Child #9    | 3
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

Nei*_*gan 13

像这样:

with recursive whosYourDaddy as (

  --start with the "anchor" row
  select
    *
  from foo
  where
    id = 9 --parameterize me

  union all

  select
    foo.*
  from foo 
  join whosYourDaddy on whosYourDaddy.parent_id = foo.id
)

select
  *
from whosYourDaddy 
order by
  id;
Run Code Online (Sandbox Code Playgroud)

结果:

id  name      parent_id
-----------------------
1   Root      (null)
3   Parent 3  1
9   Child 9   3
Run Code Online (Sandbox Code Playgroud)

码:

http://sqlfiddle.com/#!15/a5fb9/12

  • 谢谢,@neil-mcguian,做到了!我必须将“union all”更改为“union”,因为查询不断运行,直到我的计算机空间不足。仅使用“union”,查询运行得很快,结果正是我想要的。 (2认同)