Postgres在创建查询计划时不使用HASH索引

时间:2016-08-30 07:06:12

标签: postgresql join query-optimization postgresql-9.1 sql-execution-plan

我在主题strong_id上的表 t_posts 上创建了 HASH索引,这是表 t_topics

中的主键
select * FROM t_topics
 JOIN t_posts ON  t_topics.topics_id = t_posts.topics_id 

当我执行上述查询时,生成的计划

Hash Join  (cost=12258.02..346305.42 rows=1813743 width=520)
  Hash Cond: (t_posts.topics_id = t_topics.topics_id)
  ->  Seq Scan on t_posts  (cost=0.00..114209.43 rows=1813743 width=408)
  ->  Hash  (cost=5939.12..5939.12 rows=217112 width=112)"
        ->  Seq Scan on t_topics  (cost=0.00..5939.12 rows=217112 width=112)

enter image description here

计划应该顺序扫描t_topics并在t_posts上使用HASH索引 t_topics 并执行JOIN。为什么查询计划是这样生成的?

1 个答案:

答案 0 :(得分:2)

此索引仅对嵌套循环连接有帮助,但规划器选择执行散列连接,其中连接条件的索引没有帮助。<登记/> 从行数估计来看,我会说计划者是对的。

您可以通过将enable_hashjoinenable_mergejoin设置为off并再次尝试来检查嵌套循环连接是否可以使用您的索引。