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

recursive query postgres12 gives [42P19] ERROR

我正在使用一些 parent/child 玩具辛普森一家数据在 postgres postgres 12 中学习递归。

创建语句如下:

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');

现在我想创建一个 table,其中有一列用于祖先,一列用于后代,应该如下所示:

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;

我理解这个错误,但我不明白我如何在不创建中间体 table 的情况下实现我想要的,而中间体 table 是 Ancestor 与自身的叉积。

您需要将父 table 加入 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;

通常在递归 CTE 中,您加入 原始 table 而不是自我加入递归 table.

如果你这样做,你会得到你想要的:

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;

Here 是一个 db<>fiddle.