我有一个问题,关于查询中的 CTE 是只运行一次还是每次加入时都运行。
导致我们在 postgres 指标中面临 CPU 消耗问题。
如果它只运行一次那么很好。如果不是,我们需要优化查询。在 postgres SQL 中有什么方法可以使 CTE 只运行一次?
下面是示例查询。为简洁起见,删除了每个 cte 中的复杂逻辑,并避免出现混淆。主要的 CTE(即本例中的 current_student_temp)是至关重要的,需要用于进一步处理。
with current_student_temp as (
select * from
(select sd.student_id ,sd.school_id,
sd.first_name ,sd.last_name ,
ROW_NUMBER()
OVER (PARTITION by sd.student_id
ORDER BY sd.school_id ) AS rowNum
from basics.student_appt_details sd
)school_appts_for_student
where rowNum=1
),
race_cd_temp as (
select rc.student_id ,rc.race_cd as race
from basics.race_details rc
inner join current_student_temp cst on cst.student_id = rc.student_id
--will current_student_temp run again here? breakpoint-1
),
citizenship_temp as (
select ct.student_id ,ct.citizenship as citizenship
from basics.citizenship_details ct
inner join current_student_temp cst on cst.student_id = ct.student_id
--will current_student_temp run again here? breakpoint-2
),
gender_temp as (
select gt.student_id ,gt.gender as gender
from basics.gender_details gt
inner join current_student_temp cst on cst.student_id = gt.student_id
--will current_student_temp run again here? breakpoint-3
)
select * from basics.person
left join current_student_temp cst on cst.student_id = person.student_id
left join race_cd_temp rct on rct.student_id = person.student_id
left join citizenship_temp ct on ct.student_id = person.student_id
left join gender_temp gt on gt.student_id = person.student_id
非常感谢任何意见。
https://www.postgresql.org/docs/current/sql-select.html 说:
计算
列表中的所有查询。这些有效地充当可以在WITH
列表中引用的临时表。在FROM
中被多次引用的WITH
查询只被计算一次,除非用FROM
另有说明。NOT MATERIALIZED
(强调我的)