递归查询postgres12给出[42p19]错误

nszi6y05  于 2021-08-09  发布在  Java
关注(0)|答案(2)|浏览(270)

我正在学习PostgresPostgres12中的递归,使用一些父/子玩具辛普森一家的数据。
下面是create语句:

create table Parent(
    parent varchar,
    child varchar
);

insert into Parent (parent, child) values
                                          ('homer', 'bart'),
                                          ('homer', 'lisa'),
                                          ('marge', 'bart'),
                                          ('marge', 'lisa'),
                                          ('abe', 'homer'),
                                          ('ape', 'abe');

现在我想创建一个表,其中有一列表示祖先,一列表示后代,如下所示:

ancestor | descendant
----------------------
homer    | bart
homer    | lisa
marge    | bart
marge    | lisa
abe      | homer
ape      | abe
ape      | homer
abe      | bart
abe      | lisa
ape      | bart
ape      | lisa

我的解决方案产生了这个错误: [42P19] ERROR: recursive reference to query "ancestor" must not appear more than once 这是我的密码:

with recursive
Ancestor(ancestor, descendant) as
    ((select parent, child from Parent)
     union
     (select a1.ancestor, a2.descendant
      from Ancestor a1, Ancestor a2
      where a1.descendant = a2.ancestor))
select *
from Ancestor;

我理解这个错误,但是我不明白如果不创建一个包含祖先与自身的交叉积的中间表,我怎么能实现我想要的。

kiayqfof

kiayqfof1#

通常,在递归cte中,连接到原始表,而不是自连接到递归表。
如果你这样做,你会得到你想要的:

with recursive Ancestor(ancestor, descendant) as (
      select parent, child
      from Parent
      union all
      select a.ancestor, p.child
      from Ancestor a join
           parent p
           on a.descendant = p.parent
     )
select *
from Ancestor;

这是一把小提琴。

wlwcrazw

wlwcrazw2#

您需要将父表联接到cte:

with recursive Ancestor as (
  select parent, child 
  from Parent
  where parent = 'abe'

  union

  select p.parent, p.child
  from parent p
     join ancestor a on a.child = p.parent
)
select *
from Ancestor;

相关问题