首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在PostgreSQL中基于解释分析优化查询?

问如何在PostgreSQL中基于解释分析优化查询?
EN

Database Administration用户
提问于 2019-05-21 02:17:24
回答 1查看 46关注 0票数 0

我正在通过EXPLAIN ANALYZE运行以下查询,但运行起来需要很长时间。基于EXPLAIN ANALYZE的输出,我可以对我的表做些什么来使这个查询更快地执行?

代码语言:javascript
复制
select count(amount), sum(amount) 
from mytable 
where color_code = 5 and shade_type = 'Light';

EXPLAIN ANALYZE输出:

代码语言:javascript
复制
 Finalize Aggregate  (cost=946640.31..946640.32 rows=1 width=40) (actual time=4799.256..4799.257 rows=1 loops=1)
   ->  Gather  (cost=946640.09..946640.30 rows=2 width=40) (actual time=4799.191..4800.566 rows=3 loops=1)
         Workers Planned: 2
         Workers Launched: 2
         ->  Partial Aggregate  (cost=945640.09..945640.10 rows=1 width=40) (actual time=4797.002..4797.003 rows=1 loops=3)
               ->  Parallel Seq Scan on mytable  (cost=0.00..945573.39 rows=13338 width=6) (actual time=656.722..4791.404 rows=10103 loops=3)
                     Filter: ((color_code = 5) AND ((shade_type)::text = 'Light'::text))
                     Rows Removed by Filter: 4888180
 Planning time: 0.257 ms
 Execution time: 4800.661 ms
(10 rows)
EN

回答 1

Database Administration用户

回答已采纳

发布于 2019-05-21 05:50:00

您需要此索引才能使查询快速:

代码语言:javascript
复制
CREATE INDEX ON mytable (color_code, shade_type);

如果希望仅扫描索引,则可以使用

代码语言:javascript
复制
CREATE INDEX ON mytable (color_code, shade_type) INCLUDE (amount);

但是,只有当表经常被清空,并且您不需要对amount列进行热更新时,这才会有用。

票数 1
EN
页面原文内容由Database Administration提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://dba.stackexchange.com/questions/238643

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档