相关疑难解决方法(0)

查询优化或缺少索引?

我有这个查询将一些数据从t2into聚合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

3
推荐指数
1
解决办法
1528
查看次数

标签 统计

postgresql ×1