简体   繁体   English

PostgreSQL嵌套CTE和UNION

[英]PostgreSQL nested CTE and UNION

I'm trying to learn SQL, using PostgreSQL 9.1.3. 我正在尝试使用PostgreSQL 9.1.3学习SQL。 I would like to understand some behavior that strikes me as inconsistent. 我想了解一些让我觉得不一致的行为。 To wit: 以机智:

This works: 这有效:

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

I get this: 我明白了:

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

This works: 这有效:

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

Result: 结果:

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

This also works: 这也有效:

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

I get this: 我明白了:

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

But this does not work: 但是,这并不工作:

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

Result: 结果:

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

To my way of thinking, either the last one should succeed or one of the other ones should fail. 按照我的思维方式,要么最后一个应该成功,要么其他一个应该失败。 I don't see the pattern. 我没有看到这种模式。 Is there some general rule that would enable me to predict what combinations of nested CTEs and UNIONs will or will not work? 是否有一些通用规则可以让我预测嵌套CTE和UNION的组合将会或不会起作用?

The mystery is solved: the behavior I was observing is a known bug. 这个谜团得到了解决:我观察到的行为是一个已知的错误。 I sent the same original post to a PostgreSQL-specific list and got this answer: 我将相同的原始帖子发送到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. 这是一个错误:-(。解析分析代码似乎认为WITH只能附加到顶级或设置操作树中的叶级SELECT;但语法遵循SQL标准,不会说这样的事情。 WITH被接受,并附加到中间级UNION,它在语法上应该去,然后在解析分析时完全被忽略。将看到修复它。

  regards, tom lane 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM