从表更新 - 不使用索引(第9.1页)

时间:2014-10-02 18:21:07

标签: sql postgresql indexing postgresql-9.1 database-performance

UPDATE
 npi_bn
SET
  count = npi_bn_count.count
FROM 
  npi_bn_count
WHERE
  npi_bn.bn = npi_bn_count.bn

问题:此更新查询未使用我的索引(在20密耳行上非常慢)。它相当直接的文本连接,并且两个表中的两个字段都被编入索引。如何让规划人员使用我的索引?

EXPLAIN
Update on npi_bn  (cost=99.59..1045037.73 rows=20826256 width=75)
  ->  Hash Join  (cost=99.59..1045037.73 rows=20826256 width=75)
        Hash Cond: (npi_bn.bn = npi_bn_count.bn)
        ->  Seq Scan on npi_bn  (cost=0.00..706474.20 rows=20832220 width=65)
        ->  Hash  (cost=55.93..55.93 rows=3493 width=22)
              ->  Seq Scan on npi_bn_count  (cost=0.00..55.93 rows=3493 width=22)

已经尝试:我已多次重建索引,有/无text_pattern_ops并运行了分析

信息:Postgres 9.1(64位)我有一个表格,其中文本值多次出现,我计算了这些值(它们出现的次数)并存储在另一个表格中。我想用计数值更新主表,所以每次看到值" abc"在计数列中,它列出了它在表格中显示的次数

的索引:

CREATE INDEX idx_npi_bn_name
  ON npi_bn
  USING btree (bn text_pattern_ops);

CREATE INDEX idx_npi_bn_count_name
  ON npi_bn_count
  USING btree (bn text_pattern_ops);

示例数据:

╔════╦══════════════╦══════╗
║ ID ║  bn (text)   ║ count║
╠════╬══════════════╬══════╣
║  1 ║ abc          ║ 2    ║
║  2 ║ efg          ║ 1    ║
║  3 ║ abc          ║ 2    ║
║  4 ║ xyz          ║ 1    ║
╚════╩══════════════╩══════╝

MAIN TABLE = npi_bn

  • id(int)
  • bn(text) - 许多重复
  • count(int) - 我要更新的字段

在TABLE中存储的计数= npi_bn_count

  • bn(text)
  • count(int) - 计数值在这里

1 个答案:

答案 0 :(得分:3)

没有证据表明索引可以帮助解决此问题。

您正在阅读和处理所有行。散列连接或合并连接可能会更快。

如果您想进行比较,请尝试(用于测试目的)设置:

enable_hashjoin = off
enable_mergejoin = off

如果它们适合,它可能会使用您的索引......并且速度更慢。

如果速度更快,那么random_page_cost可能无法反映机器的真实表现,而且应该低得多。