【发布时间】:2014-05-03 21:25:57
【问题描述】:
我有一个大约 2300 万行的表 (sales_points)。它在 (store_id, book_id) 上有一个 b-tree 索引。我希望以下查询使用该索引,但 EXPLAIN 表明它正在执行顺序扫描:
select distinct store_id, book_id from sales_points
这是 EXPLAIN 的输出:
Unique (cost=2050448.88..2086120.31 rows=861604 width=8)
-> Sort (cost=2050448.88..2062339.35 rows=23780957 width=8)
Sort Key: store_id, book_id
-> Seq Scan on sales_points (cost=0.00..1003261.87 rows=23780957 width=8)
如果我这样做,它确实会使用索引:
select distinct book_id from sales_points where store_id = 1
这是此查询的 EXPLAIN 输出:
HashAggregate (cost=999671.02..999672.78 rows=587 width=4)
-> Bitmap Heap Scan on sales_points (cost=55576.17..998149.04 rows=3043963 width=4)
Recheck Cond: (store_id = 1)
-> Bitmap Index Scan on index_sales_points_on_store_id_and_book_id (cost=0.00..55423.97 rows=3043963 width=0)
Index Cond: (store_id = 1)
这是 DDL 表:
CREATE TABLE sales_points
(
id serial NOT NULL,
book_id integer,
store_id integer,
date date,
created_at timestamp without time zone,
updated_at timestamp without time zone,
avg_list_price numeric(5,2),
royalty_amt numeric(9,2),
currency character varying(255),
settlement_date date,
paid_sales integer,
paid_returns integer,
free_sales integer,
free_returns integer,
lent_units integer,
lending_revenue numeric(9,2),
is_placeholder boolean,
distributor_id integer,
source1_id integer,
source2_id integer,
source3_id integer,
CONSTRAINT sales_points_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
这是索引表达式:
CREATE INDEX index_sales_points_on_store_id_and_book_id
ON sales_points
USING btree
(store_id, book_id);
那么为什么 Postgres 不使用索引来加速 SELECT 呢?
【问题讨论】:
-
表的定义是什么?你能发布 DDL 吗?
标签: performance postgresql postgresql-9.2 heroku-postgres