我有一张大桌(~44 GB,421631931行)。
我正在尝试优化此类SQL查询:
SELECT fid, sid, dsc_entry, clstr_first_entry, date_part('epoch',start_time)::numeric(20,7) AS time_epoch
FROM frames
WHERE (sid = 1)
AND start_time <= to_timestamp('1471161210.776')
ORDER BY start_time DESC
LIMIT 1;
到目前为止,我已在列start_time
上设置了索引:
"idx_start_time" btree (start_time) CLUSTER
当我运行EXPLAIN
时,我得到了这个计划:
Limit (cost=0.57..0.92 rows=1 width=24)
-> Index Scan Backward using idx_start_time on frames (cost=0.57..19347837.35 rows=55108378 width=24)
Index Cond: (start_time <= '2016-08-14 09:53:30.776+02'::timestamp with time zone)
Filter: (sid = 1)
这对我来说很好看(请注意,我以前从未试图以这种方式优化数据库),但查询仍需要大约80秒才能完成。
请你指点一下,我怎样才能加快速度呢? (磁盘空间不是问题)
谢谢, 彼得。
答案 0 :(得分:0)
对于此查询:
SELECT fid, sid, dsc_entry, clstr_first_entry,
date_part('epoch', start_time)::numeric(20,7) AS time_epoch
FROM frames
WHERE (sid = 1) AND start_time <= to_timestamp('1471161210.776')
ORDER BY start_time DESC
LIMIT 1;
我建议frames(sid, start_time)
上的索引。