2013-10-17 52 views
3

此查询递归CTE产生从1号至4问题与PostgreSQL的

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; 

它给

ERROR: syntax error at or near "z"

我在这里做错了什么?

+1

后来相关的更多细节的答案: http://stackoverflow.com/a/35249370/939860 –

回答

3

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