2013-10-17 55 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