我有两个表。新闻表有7m记录,news_publish表有70m记录 当我执行这个查询花费了大量的时间并且很慢。 我增加了三个索引进行调整,但查询速度很慢。 当我谷歌这个问题,我发现有人建议改变统计到1000,我恰克它,但问题是还没有postgresql日期提交查询性能
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);
后添加此指标和运行讲解分析我得到这个解释
"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 –
我改变它我添加解释在https://explain.depesz.com/s/Gym –
CREATE INDEX“p.id”ON khb_news_publish USING btree(id DESC);'恕我直言,这应该是一个主键(这将执行一个**唯一**索引)。与其他表类似:首先限制PK + FK,而不是为FK添加支持索引,而不是为其他候选键添加唯一索引,而不是添加一些附加索引来支持典型查询。 – wildplasser