我创建了一个 36M 行的表,列上有一个索引type:
CREATE TABLE items AS
SELECT
(random()*36000000)::integer AS id,
(random()*10000)::integer AS type,
md5(random()::text) AS s
FROM
generate_series(1,36000000);
CREATE INDEX items_type_idx ON items USING btree ("type");
Run Code Online (Sandbox Code Playgroud)
我运行这个简单的查询并期望 postgresql 使用我的索引:
explain select count(*) from "items" group by "type";
Run Code Online (Sandbox Code Playgroud)
但是查询计划器决定使用 Seq Scan 代替:
HashAggregate (cost=734592.00..734627.90 rows=3590 width=12) (actual time=6477.913..6478.344 rows=3601 loops=1)
Group Key: type
-> Seq Scan on items (cost=0.00..554593.00 rows=35999800 width=4) (actual time=0.044..1820.522 rows=36000000 loops=1)
Planning time: 0.107 ms
Execution time: 6478.525 ms
Run Code Online (Sandbox Code Playgroud)
无解释时间: 5s 979ms
我从这里 …