postgresql优化案例二

文章目录

  • SQL语句
  • 查看改善前执行计划:
  • 解决方案
  • 改善后执行计划

SQL语句

	SELECT facility, workno, workseq, aufnr, productkind, workdate, stepname, shift, resourcegroup, resource as mesresource, 
	plnbez, zzstylcode, zzmdnam, zzatcolr, zzmdmark, partcolor, component as mescomponent, namezf, nameen, formulano, zzoutsolmod, 
	zzmidsolmod, wosize, bmeng, perqty, meins, gamng, leftqty, rightqty, outboundtime, processmk, web_processmk, universalstate 
	FROM outboundbwork 
	WHERE (web_processmk isnull or web_processmk <> $1) and outboundtime >= (($2)) and outboundtime <= (($3))

查看改善前执行计划:

cmfdb=#
prepare p1 as
SELECT facility, workno, workseq, aufnr, productkind, workdate, stepname, shift, resourcegroup, resource as mesresource, plnbez, zzstylcode, zzmdnam, zzatcolr, zzmdmark, partcolor, component as mescomponent, namezf, nameen, formulano, zzoutsolmod, 
zzmidsolmod, wosize, bmeng, perqty, meins, gamng, leftqty, rightqty, outboundtime, processmk, web_processmk, universalstate 
FROM outboundbwork 
WHERE (web_processmk isnull or web_processmk <> $1) and outboundtime >= (($2)) and outboundtime <= (($3))
PREPARE
cmfdb=# explain (analyze) execute p1('','','');
                                                                         QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------
 Gather  (cost=1000.00..79510.77 rows=1 width=244) (actual time=483.852..534.530 rows=0 loops=1)
   Workers Planned: 2
   Workers Launched: 2
   ->  Parallel Seq Scan on outboundbwork  (cost=0.00..78510.67 rows=1 width=244) (actual time=479.191..479.192 rows=0 loops=3)
         Filter: (((web_processmk IS NULL) OR (web_processmk <> ''::bpchar)) AND ((outboundtime)::text >= ''::text) AND ((outboundtime)::text <= ''::text))
         Rows Removed by Filter: 573202
 Planning time: 1.467 ms
 Execution time: 534.694 ms
(8 rows)

解决方案

从上面的执行计划输出,可以看出针对有几十万数据的表选择了全表扫描,因此创建合适的索引是好的选择之一

create index idx_outboundbwork_outbound_time on outboundbwork(outboundtime)

改善后执行计划

cmfdb=# explain (analyze) execute p1('','','');
                                                                   QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------------------------------
 Index Scan using idx_outboundbwork_outbound_time on outboundbwork  (cost=0.43..8.45 rows=1 width=244) (actual time=0.007..0.008 rows=0 loops=1)
   Index Cond: (((outboundtime)::text >= ''::text) AND ((outboundtime)::text <= ''::text))
   Filter: ((web_processmk IS NULL) OR (web_processmk <> ''::bpchar))
 Planning time: 0.956 ms
 Execution time: 0.040 ms
(5 rows)

你可能感兴趣的:(Postgresql,数据库)