小编典典

PostgreSQL中递归CTE的问题

sql

此查询生成从1到4的数字。

with recursive z(q) as (
  select 1
  union all
  select q + 1 from z where q < 4
  )
select * from z;

但是,如果我对此进行修改,

with x as (
  select 1 y
  ),
recursive z(q) as (
  select y from x
  union all
  select q + 1 from z where q < 4
  )
select * from z;

它给

错误:“ z”处或附近的语法错误

我在这里做错了什么?


阅读 154

收藏
2021-04-14

共1个答案

小编典典

我认为这是因为RECURSIVE是WITH语句的修饰符,而不是常用表表达式的属性z,因此您可以像这样使用它:

with recursive
x as (
  select 1 y
),
z(q) as (
  select y from x
  union all
  select q + 1 from z where q < 4
)
select * from z;

[sql fiddle demo](http://sqlfiddle.com/#!12/d41d8/1940)

2021-04-14