我正在从“订单簿活动”创建订单簿的快照。以下示例演示了该任务的本质:
CREATE TABLE t AS SELECT i.event_id, 10000*(round(i.event_id/10000,0)+1) AS last_event_id FROM ( SELECT * FROM generate_series(1,1000000) AS event_id ) i;
ALTER TABLE t ADD PRIMARY KEY (event_id);
CREATE INDEX t_idx ON t USING btree (last_event_id ASC NULLS LAST);
EXPLAIN ANALYZE SELECT * FROM T WHERE event_id <= 80001 and last_event_id >= 80001;
EXPLAIN ANALYZE
的输出如下:
QUERY PLAN
-----------------------------------------------------------------------------
Index Scan using t_pkey on t (cost=0.42..2928.77 rows=73870 width=9) (actual time=52.526..52.529 rows=2 loops=1)
Index Cond: (event_id <= 80001)
Filter: (last_event_id >= '80001'::numeric)
Rows Removed by Filter: 79999
Planning time: 0.211 ms
Execution time: 52.578 ms
因此PostgreSQL仅使用t_pkey索引并忽略t_idx。
为什么PostgreSQL不同时使用t_pkey和t_idx?
我在Centos 7上使用PostgreSQL 9.6