这里和那里(包括 postgres web 上的官方帖子)有一些关于 9.2 之前的慢速计数(*)的讨论;不知何故,我没有找到满意的答案。
基本上我安装了 postgres 9.1,我观察到慢速 count(*) 就像
select count(*) from restaurants;
在记录超过 100k 的表上。平均请求约为 850 毫秒。好吧,我假设这是人们一直在谈论的症状,因为 postgres 9.1 及更低版本的计数缓慢,因为 postgres 9.2 具有一些新功能,例如 index-only scan。我想通过使用来自 9.1 的相同数据集并将其放在 9.2 上来对此进行实验。我调用了 count 语句,它仍然给出了 9.1 的错误结果。
explain analyze select count(*) from restaurants;
------------------------------------------------------------------
Aggregate (cost=23510.35..23510.36 rows=1 width=0) (actual time=979.960..979.961 rows=1 loops=1)
-> Seq Scan on restaurants (cost=0.00..23214.88 rows=118188 width=0) (actual time=0.050..845.097 rows=118188 loops=1)
Total runtime: 980.037 ms
谁能提出解决这个问题的可行方案?我是否需要在 postgres 上配置任何内容才能启用该功能?
附言where 子句 对我的情况也没有帮助。
最佳答案
查看索引仅扫描 wiki 条目:
- What types of queries may be satisfied by an index-only scan?
- is
count(*)
much faster now? - Why isn't my query using an index-only scan?
特别是,我引用:
It is important to realise that the planner is concerned with minimising the total cost of the query. With databases, the cost of I/O typically dominates. For that reason, "count(*) without any predicate" queries will only use an index-only scan if the index is significantly smaller than its table. This typically only happens when the table's row width is much wider than some indexes'.
另请参阅 VACUUM
和 ANALYZE
的讨论以维护可见性图。本质上,您可能希望使 VACUUM
更具攻击性,并且您将希望在首次加载表后手动 VACUUM ANALYZE
。
关于postgresql - postgresql 9.2 上的缓慢计数 (*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13855304/