【问题标题】:Am I duplicating a MySQL index or is there a value in having both?我是在复制 MySQL 索引还是两者兼而有之?
【发布时间】:2017-10-30 12:55:36
【问题描述】:

我有一个表,其中包含我要索引的几个字段:

user_id = Int that divides the data between user accounts.
item_number = Non-unique Int that a user sets when creating new items.

我有两个索引:

idx_user_id: Fields = user_id, Type = BTREE, Unique = NO
idx_user_id_item_number: Fields = user_id AND item_number, Type =
BTREE, Unique = YES

我想知道 idx_user_id 是否是不必要的,因为我们也以 user_id 开始我们的 idx_user_id_item_number,查询将使用它并获得相同的结果。我唯一担心的是,由于 idx_user_id_item_number 索引是唯一的,因此可能需要同时保留两者。

【问题讨论】:

  • 取决于您在该表上运行什么查询。如果您有查询搜索 user_id 和查询搜索 user_id, item_number 则保留两者
  • 错了。您只需要 idx_user_id_item_number。当您仅对 user_id 进行过滤时,也可以使用此索引。唯一性并不重要。

标签: mysql indexing


【解决方案1】:

(user_id) 上的索引与(user_id, item_number) 上的索引是多余的。您不需要第一个索引。您应该删除它,因为它会占用存储空间并减慢更新和插入操作。

为了建立索引,MySQL 在多列索引中使用前导列,就好像它们是独立索引一样。

但请注意,如果您在 (user_id) 上的索引是唯一索引而另一个不是,则您需要两个索引。为什么?在这种情况下,您将使用第一个索引来强制执行唯一性约束。

【讨论】:

  • 没有主键有什么原因吗?
【解决方案2】:
  • 拥有PRIMARY KEY 很重要。
  • 一个PK是UNIQUE

所以,去掉两个索引,只有

PRIMARY KEY(user_id, item_number)

【讨论】:

    猜你喜欢
    • 2014-07-20
    • 1970-01-01
    • 2013-08-17
    • 2015-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 2011-10-16
    相关资源
    最近更新 更多