给定表:
Column | Type
id | integer
latitude | numeric(9,6)
longitude | numeric(9,6)
speed | integer
equipment_id | integer
created_at | timestamp without time zone
Indexes:
"geoposition_records_pkey" PRIMARY KEY, btree (id)
该表有2000万条记录,相对而言,这不是一个很大的记录。但这会使顺序扫描变慢。
如何获得max(created_at)
每个记录的最后一条记录()equipment_id
?
我已经尝试了以下两个查询,并阅读了有关该主题的许多答案的几种变体:
select max(created_at),equipment_id from geoposition_records group by equipment_id;
select distinct on (equipment_id) equipment_id,created_at
from geoposition_records order by equipment_id, created_at desc;
我也尝试过为它创建btree索引,equipment_id,created_at
但是Postgres发现使用seqscan更快。强制enable_seqscan = off
也没有用,因为读取索引的速度与seq扫描一样慢,可能更糟。
查询必须定期运行,始终返回最后一个。
使用Postgres 9.3。
解释/分析(有170万条记录):
set enable_seqscan=true;
explain analyze select max(created_at),equipment_id from geoposition_records group by equipment_id;
"HashAggregate (cost=47803.77..47804.34 rows=57 width=12) (actual time=1935.536..1935.556 rows=58 loops=1)"
" -> Seq Scan on geoposition_records (cost=0.00..39544.51 rows=1651851 width=12) (actual time=0.029..494.296 rows=1651851 loops=1)"
"Total runtime: 1935.632 ms"
set enable_seqscan=false;
explain analyze select max(created_at),equipment_id from geoposition_records group by equipment_id;
"GroupAggregate (cost=0.00..2995933.57 rows=57 width=12) (actual time=222.034..11305.073 rows=58 loops=1)"
" -> Index Scan using geoposition_records_equipment_id_created_at_idx on geoposition_records (cost=0.00..2987673.75 rows=1651851 width=12) (actual time=0.062..10248.703 rows=1651851 loops=1)"
"Total runtime: 11305.161 ms"
NULL
值equipment_id
低于0.1%