我正在尝试使用 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 的哪些组合将起作用或不起作用?