如何加快postgresql自联接查询

时间:2016-04-05 15:50:05

标签: postgresql

我在同一张桌子上使用连接一次获得50行,但需要20秒才能获得50行。

Select Distinct ON (S1.service) S1.account,S1.stid,S1.receiver,S1.identifier,
       S1.binfo,S2.dlr_mask,S2.time,S1.msgdata,S1.msg_cost 
from sql_sent_sms S1 
left join sql_sent_sms S2 
       on S1.service = S2.service  
where  S2.time Between :senttime and :endtime 
  and S1.userid=:userid 
Order By S1.service");

我在time , service ,userid参数上创建了索引。

但它没有多大帮助。

我还应该做些什么来加快速度。

这是分析查询的结果

       EXPLAIN ANALYZE Select Distinct ON (S1.service) S1.account,S1.stid,S1.receiver,S1.identifier,S1.binfo,S2.dlr_mask,S2.time,S1.msgdata,S1.msg_cost
               from sql_sent_sms S1
               left join sql_sent_sms S2
                      on S1.service = S2.service
               where  S2.time Between '1459759193' and '1459849193'
                 and S1.userid='10412144'
               Order By S1.service , S2.dlr_mask asc limit 50;
                                                                              QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=56635220.85..56938614.70 rows=50 width=308) (actual time=1.177..1.177 rows=0 loops=1)
   ->  Unique  (cost=56635220.85..57035700.74 rows=66 width=308) (actual time=1.176..1.176 rows=0 loops=1)
         ->  Sort  (cost=56635220.85..56835460.79 rows=80095977 width=308) (actual time=1.176..1.176 rows=0 loops=1)
               Sort Key: s1.service, s2.dlr_mask
               Sort Method: quicksort  Memory: 25kB
               ->  Nested Loop  (cost=1.24..127912.78 rows=80095977 width=308) (actual time=1.166..1.166 rows=0 loops=1)
                     ->  Index Scan using idx_sentmsgbydate on sql_sent_sms s1  (cost=0.43..21247.62 rows=5765 width=292) (actual time=0.035..0.091 rows=34 loops=1)
                           Index Cond: ((userid)::text = '10412144'::text)
                     ->  Index Only Scan using idx_sentmsgandstauts on sql_sent_sms s2  (cost=0.81..18.45 rows=5 width=126) (actual time=0.030..0.030 rows=0 loops=34)
                           Index Cond: ((service = (s1.service)::text) AND ("time" >= 1459759193::bigint) AND ("time" <= 1459849193::bigint))
                           Heap Fetches: 0
 Planning time: 2.471 ms
 Execution time: 1.269 ms
(13 rows)

0 个答案:

没有答案