PostgreSQL中的递归CTE问题

时间:2013-10-17 06:57:49

标签: sql postgresql common-table-expression recursive-cte

此查询生成从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”或附近的语法错误

我在这里做错了什么?

1 个答案:

答案 0 :(得分:4)

我认为这是因为RECURSIVE is modifier of WITH statement,而不是公用表格式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