PostgreSQL中递归CTE的问题

3

这个查询生成从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
稍后相关的更多细节答案请参考:https://dev59.com/31sW5IYBdhLWcg3wOk_O#35249370 - Erwin Brandstetter
1个回答

4

我认为这是因为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


1
递归使得自引用查询在多个CTE列表中的任何一个都可以实现,而不仅仅是第一个。 - wistlo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接