我已经阅读了很多关于日期索引的文章,但我无法在时间戳上正确使用索引。
我的表:
CREATE TABLE registration
(
id_reg serial NOT NULL,
pass_uid character varying(12) NOT NULL,
direction smallint NOT NULL,
country character varying(255) NOT NULL,
fly_number character varying(10) NOT NULL,
the_date timestamp without time zone NOT NULL DEFAULT now(),
user_id integer NOT NULL,
station_number integer NOT NULL,
fir bytea,
CONSTRAINT registration_pkey PRIMARY KEY (id_reg)
)
我在the_date列上创建了索引:
CREATE INDEX ON registration ((the_date::timestamp));
但我的查询并未使用索引:
explain select * from registration where the_date between '2001-01-01 00:00:00' and '2015-12-31 00:00:00';
"Seq Scan on registration (cost=0.00..49481.00 rows=932106 width=232) (actual time=0.401..1028.491 rows=932466 loops=1)"
" Filter: ((the_date >= '2001-01-01 00:00:00'::timestamp without time zone) AND (the_date <= '2015-12-31 00:00:00'::timestamp without time zone))"
" Rows Removed by Filter: 67534"
"Planning time: 0.538 ms"
"Execution time: 1078.553 ms"
然后我删除了旧索引并创建了新索引:
CREATE INDEX ON registration ((the_date::date));
explain analyze select * from registration where the_date between '2001-01-01' and '2015-12-31';
"Seq Scan on registration (cost=0.00..49481.00 rows=932010 width=232) (actual time=0.016..738.757 rows=932466 loops=1)"
" Filter: ((the_date >= '2001-01-01 00:00:00'::timestamp without time zone) AND (the_date <= '2015-12-31 00:00:00'::timestamp without time zone))"
" Rows Removed by Filter: 67534"
"Planning time: 0.207 ms"
"Execution time: 786.233 ms"
我使用的是配备英特尔赛扬2.16 GHz双核,内存为2 GB的PC和Postgres配置:
shared_buffers=256MB
effective_cache_size=1GB,
work_mem=64MB
synchronize_commit=off.
你能帮我解决这个问题。提前致谢