我正在尝试在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 (
为什么?
答案 0 :(得分:1)
语法令人困惑。对于整个with recursive
,该条款为with
。 recursive
不是给定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小提琴。