2020-08-04 更新:
由于显然仍在定期查看此答案,因此我想提供有关情况的最新信息。我们目前正在使用带有表分区的 PG 11,timestamp并且可以轻松处理表中的数十亿行。仅索引扫描可以挽救生命,没有它就不可能。
使用 PostgreSQL 9.2,我在相对较大的表(200 多万行)上进行慢速查询时遇到问题。我没有尝试任何疯狂的事情,只是增加了历史价值。下面是查询和查询计划输出。
我的表布局:
Table "public.energy_energyentry"
Column | Type | Modifiers
-----------+--------------------------+-----------------------------------------------------------------
id | integer | not null default nextval('energy_energyentry_id_seq'::regclass)
prop_id | integer | not null
timestamp | timestamp with time zone | not null
value | double precision | not null
Indexes:
"energy_energyentry_pkey" PRIMARY KEY, btree (id)
"energy_energyentry_prop_id" btree (prop_id)
"energy_energyentry_prop_id_timestamp_idx" btree (prop_id, "timestamp")
Foreign-key constraints:
"energy_energyentry_prop_id_fkey" FOREIGN KEY (prop_id) REFERENCES gateway_peripheralproperty(id) DEFERRABLE INITIALLY DEFERRED
Run Code Online (Sandbox Code Playgroud)
数据范围从2012-01-01至今,新数据不断增加。prop_id外键中大约有 2.2k 个不同的值,均匀分布。
我注意到行估计值相差不远,但成本估计值似乎大了 …
postgresql performance index optimization postgresql-performance
我有这个查询将一些数据从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)
编辑 …