我有这个查询将一些数据从t2
into聚合t1
。这样做是为了优化我正在处理的应用程序,以便减少对数据库的查询。我选择了下面的方法来确保我不必更新t1
两次。
最大的问题是,我可能在这里遗漏了哪些索引,查询可以进一步优化吗?
update t1
set
col1 = t2.col1_count,
col2 = t2.col2_sum,
col3 = t2.col3_sum
from (
select
b.user_id, b.t1_id,
coalesce(count(b.id), 0) as col1_count,
sum(case when b.col5 = true then b.col2 else 0 end) as col2_sum,
sum(case when b.col5 = false then b.col3 else 0 end) as col3_sum
from t1 a
left join t2 b on b.t1_id = a.id
where
b.user_id = 1
group by b.user_id, b.t1_id
) as t2
where
t2.t1_id = t1.id;
Run Code Online (Sandbox Code Playgroud)
编辑 …
postgresql ×1