为什么执行我的简单查询
select count(this_.Id) as y0_ from Activity this_
花了这么长时间(这次超过 10 分钟)?
这是查询计划(EXPLAIN ANALYZE 的输出):
QUERY PLAN
Aggregate (cost=854047.36..854047.37 rows=1 width=4)
> (actual time=728525.277..728525.277 rows=1 loops=1)
-> Index Only
> Scan using activity_pkey on activity this_ (cost=0.56..805401.87
> rows=19458196 width=4) (actual time=36.961..725381.557 rows=19517989
> loops=1)
> Heap Fetches: 10351403
Total runtime: 728533.529 ms
和 PostgreSql 版本:
PostgreSQL 9.3.5 on x86_64-unknown-linux-gnu, compiled by gcc (Debian 4.7.2-5) 4.7.2, 64-bit
索引也在这里,在 Id 字段上:
ALTER TABLE public.activity
ADD CONSTRAINT activity_pkey
PRIMARY KEY (id);
最佳答案
PostgreSQL 中的仅索引扫描有时必须查看表(堆),因为索引页不包含有关元组可见性的信息。 这是从索引中获取的行数:
(actual ... rows=19517989
这就是在堆中重新检查了多少行:
Heap Fetches: 10351403
为了加快它的速度,你应该在你的 table 上运行真空:vacuum Activity
Vacuum 将更新 visibility map ,之后仅索引扫描将能够(几乎)仅使用索引页面来执行。
关于sql - 为什么仅索引扫描需要这么长时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33009865/