我正在使用postgres 9.1并且我有一个包含大约3.5M行eventtype(varchar)和eventtime(timestamp)的表 - 以及其他一些字段.只有大约20种不同的事件类型,事件时间跨度约为4年.
我想获取每种事件类型的最后一个时间戳.如果我运行如下查询:
select eventtype, max(eventtime)
from allevents
group by eventtype
Run Code Online (Sandbox Code Playgroud)
大约需要20秒.选择不同的eventtype同样慢.查询计划显示表的完整顺序扫描 - 毫不奇怪它很慢.
解释分析上面的查询给出:
HashAggregate (cost=84591.47..84591.68 rows=21 width=21) (actual time=20918.131..20918.141 rows=21 loops=1)
-> Seq Scan on allevents (cost=0.00..66117.98 rows=3694698 width=21) (actual time=0.021..4831.793 rows=3694392 loops=1)
Total runtime: 20918.204 ms
Run Code Online (Sandbox Code Playgroud)
如果我添加一个where子句来选择一个特定的事件类型,它需要40ms到150ms,这至少是不错的.
选择特定事件类型时的查询计划:
GroupAggregate (cost=343.87..24942.71 rows=1 width=21) (actual time=98.397..98.397 rows=1 loops=1)
-> Bitmap Heap Scan on allevents (cost=343.87..24871.07 rows=14325 width=21) (actual time=6.820..89.610 rows=19736 loops=1)
Recheck Cond: ((eventtype)::text = 'TEST_EVENT'::text)
-> Bitmap Index Scan on allevents_idx2 (cost=0.00..340.28 rows=14325 width=0) (actual time=6.121..6.121 …Run Code Online (Sandbox Code Playgroud)