这是我的查询:
SELECT SUM(amount) FROM bill WHERE name = 'peter'
表中有 800K+ 行。EXPLAIN ANALYZE
说:
Aggregate (cost=288570.06..288570.07 rows=1 width=4) (actual time=537213.327..537213.328 rows=1 loops=1)
-> Seq Scan on bill (cost=0.00..288320.94 rows=498251 width=4) (actual time=48385.201..535941.041 rows=800947 loops=1)
Filter: ((name)::text = 'peter'::text)
Rows Removed by Filter: 8
Total runtime: 537213.381 ms
所有行都受到影响,这是正确的。但是为什么这么久?类似的查询没有WHERE
运行得更快:
ANALYZE EXPLAIN SELECT SUM(amount) FROM bill
Aggregate (cost=137523.31..137523.31 rows=1 width=4) (actual time=2198.663..2198.664 rows=1 loops=1)
-> Index Only Scan using idx_amount on bill (cost=0.00..137274.17 rows=498268 width=4) (actual time=0.032..1223.512 rows=800955 loops=1)
Heap Fetches: 533399
Total runtime: 2198.717 ms
我有一个索引amount
和一个索引name
。我错过了任何索引吗?
附言。我设法通过添加一个新的 idex 来解决这个问题ON bill(name, amount)
。我不明白为什么它有帮助,所以让我们把这个问题留待一段时间......