优化PostgreSQL查询

时间:2018-07-09 01:55:06

标签: postgresql query-optimization

我需要帮助优化此PostgreSQL查询。我已经创建了一些索引,但是唯一使用的索引是“ cp_campaign_task_ap_index”。

EXPLAIN ANALYZE SELECT * FROM campaign_phones 
INNER JOIN campaigns ON campaigns.id = campaign_phones.campaign_id 
INNER JOIN campaign_ports ON campaign_ports.campaign_id = campaigns.id 
WHERE campaign_phones.task_id IS NULL 
AND campaign_phones.assigned_port = 2 
AND (campaigns.auto_start IS TRUE) 
AND (campaigns.starts_at_date::date <= '2018-07-08' 
AND campaigns.ends_at_date::date >= '2018-07-08') 
AND (campaign_ports.gateway_port_id = 611) 
AND (campaign_ports.op_mode != 1) 
ORDER BY campaigns.last_sent_at ASC NULLS FIRST LIMIT 1;`

命令的输出为:

Limit  (cost=26031.86..26031.87 rows=1 width=475) (actual time=2335.421..2335.421 rows=1 loops=1)
->  Sort  (cost=26031.86..26047.26 rows=6158 width=475) (actual time=2335.419..2335.419 rows=1 loops=1)
    Sort Key: campaigns.last_sent_at NULLS FIRST
    Sort Method: top-N heapsort  Memory: 25kB
        ->  Nested Loop  (cost=136.10..26001.07 rows=6158 width=475) (actual time=1.176..1510.276 rows=36666 loops=1)
            Join Filter: (campaigns.id = campaign_phones.campaign_id)
            ->  Nested Loop  (cost=0.00..28.28 rows=2 width=218) (actual time=0.163..0.435 rows=4 loops=1)
                Join Filter: (campaigns.id = campaign_ports.campaign_id)
                Rows Removed by Join Filter: 113
                ->  Seq Scan on campaign_ports  (cost=0.00..21.48 rows=9 width=55) (actual time=0.017..0.318 rows=9 loops=1)
                        Filter: ((op_mode <> 1) AND (gateway_port_id = 611))
                        Rows Removed by Filter: 823
                ->  Materialize  (cost=0.00..5.74 rows=8 width=163) (actual time=0.001..0.008 rows=13 loops=9)
                    ->  Seq Scan on campaigns  (cost=0.00..5.70 rows=8 width=163) (actual time=0.011..0.050 rows=13 loops=1)
                        Filter: ((auto_start IS TRUE) AND ((starts_at_date)::date <= '2018-07-08'::date) AND ((ends_at_date)::date >= '2018-07-08'::date))
                        Rows Removed by Filter: 22
            ->  Bitmap Heap Scan on campaign_phones  (cost=136.10..12931.82 rows=4366 width=249) (actual time=43.079..302.895 rows=9166 loops=4)
                Recheck Cond: ((campaign_id = campaign_ports.campaign_id) AND (task_id IS NULL) AND (assigned_port = 2))
                Heap Blocks: exact=6686
                ->  Bitmap Index Scan on cp_campaign_task_ap_index  (cost=0.00..135.01 rows=4366 width=0) (actual time=8.884..8.884 rows=9167 loops=4)
                    Index Cond: ((campaign_id = campaign_ports.campaign_id) AND (task_id IS NULL) AND (assigned_port = 2))

Planning time: 1.115 ms
Execution time: 2335.563 ms

“ campaign_phones”关系可能有很多行,也许有一百万行。

我不知道从哪里开始优化,也许是创建索引或更改查询结构。

谢谢。

0 个答案:

没有答案