【问题标题】:Indexing all columns which are foreign key to a table索引作为表外键的所有列
【发布时间】:2018-12-21 19:03:21
【问题描述】:
                              Table "public.policy"
 Column |  Type   | Collation | Nullable |                Default
--------+---------+-----------+----------+----------------------------------------
 pol_id | bigint  |           | not null | nextval('policy_pol_id_seq'::regclass)
 top_id | integer |           |          |
 idn_id | integer |           |          |
 rsc_id | integer |           |          |
 act_id | integer |           |          |
 tup_id | integer |           |          |

我的表结构是这样的,除了 pol_id 之外的所有列都是外键。搜索策略可以发生在任何列上,但它将使用 top_id。例如;搜索 top_id =1 和 act_id =2 的策略。 我怎样才能更好地索引这个表?可以只索引 top_id 还是可以索引所有列。 这是一个事务表。此表中的记录最多可达 100 万到 2 条。

【问题讨论】:

  • nextval('policy_pol_id_seq'::regclass) 看起来只与 Oracle 和 PostgreSQL 数据库兼容,所以我要删除 MySQL 标记。只标记您正在使用的数据库。
  • 查询总是或大部分在top_id 和除pol_id 之外的另一列上使用相等操作?
  • 1. select * from policy where top_id =1 and idn_id = 2 or 2. select * from policy where top_id =1 and act_id = 2;依此类推...或从 top_id =1 的策略中选择 *。与 top_id 的任意组合

标签: sql postgresql database-indexes


【解决方案1】:

您的描述建议了四个索引:

  • top_id, idn_id
  • top_id, rsc_idrcs_id, top_id
  • top_id, act_idact_id, top_id
  • top_id, tup_idtup_id, top_id

这与数据库无关。 Oracle 在索引上实现了一种称为“跳过扫描”的方法。这将允许您减少索引的数量。

是否真的需要这些索引实际上取决于top_id 的选择性。如果只有少数匹配项,则可能不需要每秒额外的索引键。

【讨论】:

  • 一百万条记录中,每个 top_id 最多有 10K 条记录
  • @ShashankVC 。 . .如果您想要所有这些查询的真正快速性能,这是一个相当大的数量。另一方面,四个索引增加了数据修改操作的开销。
  • 所以你是说最好在 top_id 上添加 5 个索引或索引就足够了?
  • @ShashankVC 。 . .这取决于表的使用方式以及更新的性能要求。试试这四个索引,看看它们是否满足您的需求。
猜你喜欢
  • 2021-08-09
  • 1970-01-01
  • 2018-10-02
  • 2011-02-27
  • 2020-01-03
  • 2011-05-21
  • 1970-01-01
  • 2013-08-12
  • 2022-06-20
相关资源
最近更新 更多