【问题标题】:MySQL index: what's the difference between how 2 fields are indexed?MySQL索引:2个字段的索引方式有什么区别?
【发布时间】:2011-01-09 06:52:04
【问题描述】:

我在表格中搜索时依赖于 2 个字段:field1、field2。它们在所有记录中都不是唯一的,既不是单独的也不是组合的。

所以我正在为它们添加索引:

方法一:

alter table xx add index (field1, field2);
alter table xx add index (field2);

方法二:

alter table xx add index (field1);
alter table xx add index (field2);

我的问题是这两种方法之间有什么区别(如果有的话)?对于以下每个选择查询:

select * from table xx where field1 = ??
select * from table xx where field2 = ??
select * from table xx where field1 = ?? and field2 = ??
select * from table xx where field1 = ?? or field2 = ??

哪种方法更好?

那么,哪种方法更适合这个查询?

select * from table xx where field1 = ?? and field2 = ??

【问题讨论】:

    标签: mysql database indexing


    【解决方案1】:

    对于您发布的查询,方法 1 会更好,因为复合索引 (field1, field2) 将用于带有 field1 = ?? and field2 = ?? 的查询

    截至field1 = ?? or field2 = ?? 查询 - index merge 将被尝试应用,对于此类查询选择哪种方法并不重要。

    总结一下:如果你有field1 = ?? and field2 = ?? - 那么你必须选择复合索引。

    【讨论】:

      猜你喜欢
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 2016-06-24
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 2011-07-23
      • 2021-02-10
      相关资源
      最近更新 更多