Issue with recursive CTE in PostgreSQL

谁说胖子不能爱 提交于 2019-12-01 21:59:11

问题


This query generates the numbers from 1 to 4.

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

But, if I modify it to this,

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;

It gives

ERROR: syntax error at or near "z"

What did i do wrong here?


回答1:


I think this is because RECURSIVE is modifier of WITH statement, not a property of common table expression z, so you can use it like this:

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



来源:https://stackoverflow.com/questions/19420168/issue-with-recursive-cte-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!