sql - PostgreSQL 嵌套 CTE 和 UNION

标签 sql postgresql union common-table-expression

我正在尝试使用 PostgreSQL 9.1.3 学习 SQL。我想了解一些让我觉得前后矛盾的行为。即:

这个有效:

WITH innermost AS (SELECT 2)
SELECT * FROM innermost
UNION SELECT 3;

我明白了:

 ?column? 
----------
        2
        3

这个有效:

WITH outmost AS (
        (WITH innermost AS (SELECT 2)
         SELECT * FROM innermost)
)                                
SELECT * FROM outmost;

结果:

?column? 
----------
        2

这也有效:

WITH outmost AS (
  SELECT 1
  UNION (WITH innermost AS (SELECT 2)
         SELECT * FROM innermost)
)
SELECT * FROM outmost;

我明白了:

 ?column? 
----------
        1
        2

但这有效:

WITH outmost AS (
  SELECT 1
  UNION (WITH innermost as (SELECT 2)
         SELECT * FROM innermost
         UNION SELECT 3)
)
SELECT * FROM outmost;

结果:

ERROR:  relation "innermost" does not exist
LINE 4:          SELECT * FROM innermost

按照我的想法,要么最后一个应该成功,要么另一个应该失败。我没有看到模式。是否有一些通用规则可以让我预测嵌套 CTE 和 UNION 的哪些组合有效或无效?

最佳答案

谜底已解:我观察到的行为是一个已知错误。我将相同的原始帖子发送到特定于 PostgreSQL 的列表并得到了这个答案:

This is a bug :-(. The parse analysis code seems to think that WITH can only be attached to the top level or a leaf-level SELECT within a set operation tree; but the grammar follows the SQL standard which says no such thing. The WITH gets accepted, and attached to the intermediate-level UNION which is where syntactically it should go, and then it's entirely ignored during parse analysis. Will see about fixing it.

      regards, tom lane

http://archives.postgresql.org/pgsql-novice/2012-07/msg00113.php

关于sql - PostgreSQL 嵌套 CTE 和 UNION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11741267/

相关文章:

sql - 函数不返回预期值

java - 如何使用 Ant 创建 postgresql 数据库?

sql - UNION 或 JOIN 用于从多个表中进行 SELECT

C# 最快的 2 组排序值联合

sql - 获取要显示在与其相关的列旁边的列列表

java - 在Mysql中使用If then else

MySQL View 、联合和分组依据

ruby-on-rails - 'fields' 和 'types' 是否允许用于 rails postgresql 表的名称?

sql - 将 double 转换为文本的 Postgres 创建 '1.50000000000'

Java:有没有一种简单、快速的方法来对集合进行 AND、OR 或 XOR?