【问题标题】:Recursive SQL query in PostgresPostgres 中的递归 SQL 查询
【发布时间】:2014-08-05 01:07:14
【问题描述】:

场景:

Person(pid:int,
       name:char(20),
       predecessor:int -> Person.pid
      )

示例表:

pid, name, predecessor
0,   'abc', NULL
1,   'bcd', 0
2,   'cde', 1
3,   'efg', NULL
4,   'fgh', 3

如何找到 Person 'abc' 的所有后继者?

期望的输出:

name 
'bcd'
'cde' 

非常感谢!

【问题讨论】:

标签: sql postgresql recursive-query


【解决方案1】:

您可以通过生成所有祖先然后将它们过滤掉来做到这一点。以下是您的数据示例:

with recursive cte(pid, lev, ancestor) as (
      select pid, 0, predecessor
      from person p 
      union all
      select cte.pid, lev + 1, p.predecessor
      from person p join
           cte
           on p.pid = cte.ancestor
     )
select p2.name
from cte join
     person p1
     on cte.ancestor = p1.pid join
     person p2
     on cte.pid = p2.pid
where p1.name = 'abc';

Here 是一个 SQL Fiddle。

【讨论】:

    【解决方案2】:

    只需在recursive CTE 中生成您需要的行(不是所有行的所有 祖先):

    with recursive cte as (
       select p.pid, p.name, 1 AS lvl
       from   person a
       join   person p ON p.predecessor = a.pid
       where  a.name = 'abc'
    
       union all
       select p.pid, p.name, c.lvl + 1
       from   cte    c
       join   person p ON  p.predecessor = c.pid
       )
    select name
    from   cte
    order  by lvl;
    

    SQL Fiddle.

    旁白:You don't want to use char(20). Just use text.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2014-10-29
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 2015-07-13
      相关资源
      最近更新 更多