WITH RECURSIVE SQL在PostgreSQL中失败了

时间:2016-06-27 23:50:37

标签: sql postgresql recursion

我正在尝试在PostgreSQL中执行以下递归查询,但它抱怨

with
  animals as (
    select *
    from (values
      ('cat', 'feline'),
      ('feline', 'mammal'),
      ('dog', 'canidae'),
      ('canidae', 'mammal'),
      ('mammal', 'animal')
    ) as t (child, parent)
  ),
  recursive ranimals as (
      select child, parent
      from animals
      where child = 'cat'
    union
      select child, parent
      from animals a, ranimals ra
      where ra.parent = a.child
  )
select * from ranimals;

它失败并显示以下消息:

ERROR:  syntax error at or near "ranimals"
LINE 12:   recursive ranimals as (

为什么?

1 个答案:

答案 0 :(得分:1)

语法令人困惑。对于整个with recursive,该条款为withrecursive不是给定CTE的修饰符。所以,试试这个:

with recursive
  animals as (
    select *
    from (values
      ('cat', 'feline'),
      ('feline', 'mammal'),
      ('dog', 'canidae'),
      ('canidae', 'mammal'),
      ('mammal', 'animal')
    ) as t (child, parent)
  ),
  ranimals as (
      select child, parent
      from animals
      where child = 'cat'
    union all
      select ra.child, a.parent
      from animals a join
           ranimals ra
           on ra.parent = a.child
  )
select * from ranimals;

我还修复了join语法,修复了select以使用列的别名表,并将union更改为union all

此版本实际运行。 Here是一个SQL小提琴。