PostgreSQL嵌套CTE和UNION

我正在尝试学习sql,使用Postgresql 9.1.3。我想了解一些令我震惊的行为是不一致的。以机智:

这样做:

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.

06000

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

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...