相关疑难解决方法(0)

优化对一系列时间戳的查询(两列)

我在 Ubuntu 12.04 上使用 PostgreSQL 9.1。

我需要在一个时间范围内选择记录:我的表time_limits有两个timestamp字段和一个integer属性。我的实际表中还有其他列与此查询无关。

create table (
   start_date_time timestamp,
   end_date_time timestamp, 
   id_phi integer, 
   primary key(start_date_time, end_date_time,id_phi);
Run Code Online (Sandbox Code Playgroud)

该表包含大约 200 万条记录。

像下面这样的查询花费了大量的时间:

select * from time_limits as t 
where t.id_phi=0 
and t.start_date_time <= timestamp'2010-08-08 00:00:00'
and t.end_date_time   >= timestamp'2010-08-08 00:05:00';
Run Code Online (Sandbox Code Playgroud)

所以我尝试添加另一个索引 - PK的倒数:

create index idx_inversed on time_limits(id_phi, start_date_time, end_date_time);
Run Code Online (Sandbox Code Playgroud)

我的印象是性能有所提高:访问表中间记录的时间似乎更合理:介于 40 到 90 秒之间。

但是对于时间范围中间的值,它仍然是几十秒。在针对表格末尾时(按时间顺序),还有两次。

explain analyze第一次尝试得到这个查询计划:

 Bitmap Heap Scan on time_limits  (cost=4730.38..22465.32 rows=62682 width=36) (actual time=44.446..44.446 rows=0 loops=1)
   Recheck …
Run Code Online (Sandbox Code Playgroud)

postgresql index optimization explain postgresql-9.1

129
推荐指数
2
解决办法
13万
查看次数