我有一个 PostgreSQL 9.3 表,其中包含一些数字和一些附加数据:
CREATE TABLE mytable (
myid BIGINT,
somedata BYTEA
)
Run Code Online (Sandbox Code Playgroud)
该表目前有大约 10M 条记录,占用 1GB 磁盘空间。myid
不连续。
我想计算 100000 个连续数字的每个块中有多少行:
SELECT myid/100000 AS block, count(*) AS total FROM mytable GROUP BY myid/100000;
Run Code Online (Sandbox Code Playgroud)
这将返回大约 3500 行。
我注意到某个索引的存在显着加快了这个查询,即使查询计划根本没有提到它。没有索引的查询计划:
db=> EXPLAIN (ANALYZE TRUE, VERBOSE TRUE) SELECT myid/100000 AS block, count(*) AS total FROM mytable GROUP BY myid/100000;
QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------
GroupAggregate (cost=1636639.92..1709958.65 rows=496942 width=8) (actual time=6783.763..8888.841 rows=3460 loops=1)
Output: ((myid / 100000)), count(*)
-> Sort (cost=1636639.92..1659008.91 rows=8947594 width=8) (actual time=6783.752..8005.831 …
Run Code Online (Sandbox Code Playgroud) 我COUNT(*)
在 PostgreSQL 中有一个经常运行的查询,看起来像:
SELECT COUNT(*)
FROM customer
WHERE source_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
Run Code Online (Sandbox Code Playgroud)
此查询需要 30-60 秒来运行并搜索数百万条记录。
EXPLAIN ANALYZE
显示它正在执行顺序扫描,因此我创建了索引:
CREATE INDEX customer_by_source ON customer (source_id)
WHERE source_id IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
Run Code Online (Sandbox Code Playgroud)
但是,EXPLAIN ANALYZE
仍然显示它正在执行顺序扫描并且没有使用索引。
如何加快此查询并使其使用索引?
编辑:我的 Postgres 版本是 9.3.3。该表有大约 2000 万条记录,在每个 source_id 之间平均分配,其中另外 5 条未包含在列表中。
postgresql performance index-tuning postgresql-9.3 postgresql-performance
是否可以reltuples
使用附加条件查询给定表的列table.name LIKE 'hello%'
?
目前在我更大的表上,SELECT count(*)
查询需要很长时间,我不需要确切的计数。所以我想知道是否可以WHERE
在 the 中添加子句reltuples
?