实现说明
实际执行的是 SELECT——涉及的对象是 generate_series、src、picks。
机制上由这些部分组成:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;WHERE 只放行满足条件的行进入这条语句。
常见问题
它引用了哪些表或 CTE?
引用的是 generate_series、src、picks。
代码示例
-- volatile 函数让 planner 无法把 CTE 内联(fold)进主查询:
-- 带 random() 的 CTE 被物化,引用两次也只求值一次(evaluated only once),
-- 两个引用读到同一批行
-- 文档:SELECT containing no volatile functions can be folded into the parent query;
-- WITH queries are normally evaluated only once per execution of the parent
-- query, even if referred to more than once
WITH src AS (
SELECT g, random() AS r
FROM generate_series(1, 3) g
),
picks AS (
SELECT
(SELECT r FROM src WHERE g = 1) AS first_read,
(SELECT r FROM src WHERE g = 1) AS second_read
)
SELECT
first_read,
second_read,
first_read = second_read AS same_value -- 恒为 true:物化后只算一次
FROM picks;