sql - PostgreSQL 中的递归 CTE 问题

标签 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;

它给了

ERROR: syntax error at or near "z"

我做错了什么?

最佳答案

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

关于sql - PostgreSQL 中的递归 CTE 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19420168/

相关文章:

sql - 如何在 SQL Server 中根据年份对记录进行分组

postgresql - 日期postgres之间的 double 月数

TSQL 递归更新?

mysql - SQL - 即使 LEFT JOIN 失败也返回行

mysql - 字符串外键更改的理论错误

java - 在存储过程执行期间设置参数

sql - 窗口函数或公用表表达式 : count previous rows within range

javascript - 如何将数据库的多个表值提取到动态选择框中

ruby-on-rails - 给定特定的纬度/经度,如何计算出与纽约市附近地铁入口的距离?

sql-server-2008 - 在哪里使用 ROWLOCK、READPAST 和 CTE、子查询和更新?