微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/postgresql/192913.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐