postgresql日期提交查询性能

时间:2016-05-15 10:00:47

标签: postgresql sql-tuning

我有两张桌子。新闻表有7m记录,news_publish表有70m记录 当我执行此查询时花费了大量的时间并且非常慢。 我添加三个索引进行调优但查询速度很慢。 当我谷歌这个问题时,我发现有人建议将统计数据更改为1000并且我一试,但问题还没有

alter table khb_news alter submitteddate set statistics 1000;

SELECT  n.id as newsid ,n.title,p.submitteddate as publishdate,
    n.summary ,n.smallImageid  ,
    n.classification ,n.submitteddate as newsdate,
    p.toorganizationid

from  khb_news  n  
     join   khb_news_publish p    
        on n.id=p.newsid    
    left join dataitem b on b.id=n.classification 

where  
    n.classification in (1) and  n.newstype=60  
    AND n.submitteddate    >= '2014/06/01'::timestamp AND   n.submitteddate <'2014/08/01'::timestamp and p.toorganizationid=123123
order by p.id desc

limit 10 offset 0

索引是:

CREATE INDEX "p.id"
ON khb_news_publish
USING btree
(id DESC);

CREATE INDEX idx_toorganization
ON khb_news_publish
USING btree
(toorganizationid);


CREATE INDEX "idx_n.classification_n.newstype_n.submitteddate"
ON khb_news
USING btree
(classification, newstype, submitteddate);

添加此索引后运行explain analyze我得到这个解释

"Limit  (cost=0.99..10100.13 rows=10 width=284) (actual time=24711.831..24712.849 rows=10 loops=1)"
        "  ->  Nested Loop  (cost=0.99..5946373.12 rows=5888 width=284) (actual time=24711.827..24712.837 rows=10 loops=1)"
        "        ->  Index Scan using "p.id" on khb_news_publish p  (cost=0.56..4748906.31 rows=380294 width=32) (actual time=2.068..23338.731 rows=194209 loops=1)"
        "              Filter: (toorganizationid = 95607)"
        "              Rows Removed by Filter: 36333074"
        "        ->  Index Scan using khb_news_pkey on khb_news n  (cost=0.43..3.14 rows=1 width=260) (actual time=0.006..0.006 rows=0 loops=194209)"
        "              Index Cond: (id = p.newsid)"
        "              Filter: ((submitteddate >= '2014-06-01 00:00:00'::timestamp without time zone) AND (submitteddate < '2014-08-01 00:00:00'::timestamp without time zone) AND (newstype = 60) AND (classification = ANY ('{19,20,21}'::bigint[])))"
        "              Rows Removed by Filter: 1"
        "Planning time: 3.871 ms"
        "Execution time: 24712.982 ms"

我在https://explain.depesz.com/s/Gym中添加了解释 如何更改查询以使其更快?

1 个答案:

答案 0 :(得分:2)

您应该首先在khb_news_publish(toorganizationid,id)上创建索引

CREATE INDEX idx_toorganization_id
ON khb_news_publish
USING btree
(toorganizationid, id);

这应解决问题,但您可能还需要索引:

CREATE INDEX idx_id_classification_newstype_submitteddate
ON khb_news
USING btree
(classification, newstype, submitteddate, id);