【问题标题】:Postgres does not use HASH index while creating query planPostgres 在创建查询计划时不使用 HASH 索引
【发布时间】:2017-01-06 08:25:00
【问题描述】:

我在表 t_posts 的列 topic_id 上创建了一个 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)

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

【问题讨论】:

  • topics_id 列是什么数据类型?你那里有什么数据?
  • 您从两个表中选择 all 列和 all 行。对两个表进行顺序扫描是最有效的做法。使用索引实际上会使事情变慢。
  • @Boris 列是整数类型

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


【解决方案1】:

这个索引只对嵌套循环连接有帮助,但规划器选择执行散列连接,其中连接条件上的索引无济于事。 从行数估计来看,我会说计划者是对的。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多