为什么不使用索引?

时间:2019-07-06 20:37:24

标签: postgresql

我有疑问:

EXPLAIN ANALYSE
SELECT * FROM "order_bt" o
LEFT JOIN agreement a ON a.id = o.agreement_id

两个表都有索引:

"order_idx_agreement_id" btree (agreement_id)
"agreement_pkey" PRIMARY KEY, btree (id)

但是explain analyseSeq Scan on agreement a为什么?

                                                       QUERY PLAN                                                        
-------------------------------------------------------------------------------------------------------------------------
 Hash Left Join  (cost=36.97..199.70 rows=3702 width=193) (actual time=0.961..8.422 rows=3702 loops=1)
   Hash Cond: (o.agreement_id = a.id)
   ->  Seq Scan on order_bt o  (cost=0.00..116.02 rows=3702 width=136) (actual time=0.025..3.566 rows=3702 loops=1)
   ->  Hash  (cost=22.54..22.54 rows=1154 width=57) (actual time=0.912..0.912 rows=1154 loops=1)
         Buckets: 2048  Batches: 1  Memory Usage: 104kB
         ->  Seq Scan on agreement a  (cost=0.00..22.54 rows=1154 width=57) (actual time=0.019..0.397 rows=1154 loops=1)
 Planning time: 0.785 ms
 Execution time: 8.886 ms
(8 rows)

2 个答案:

答案 0 :(得分:3)

只有〜1000行,您正在选择所有列。如果确实使用了索引,则必须返回表以获取其余数据。对于这么小的表,只扫描整个内容会更快,尤其是因为看起来您无论如何都在选择协议表的每一行和每一列。

答案 1 :(得分:2)

哈希联接不利用索引,它们顺序扫描两个关系。

只有嵌套循环联接和合并联接才能在联接列上使用索引。

PostgreSQL刚刚决定使用索引效率不高,因为哈希联接是最快的方法。由于估算是准确的,因此可能做出了正确的决定。

如果表保持很小并且您不需要其他用途,则可以删除索引。

相关问题