我正在尝试使用 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/