具有较少可能值的字段的索引

时间:2016-04-04 13:37:58

标签: mysql optimization indexing

我有一张由数百万条记录组成的表格,我将在FieldAFieldB选择一个位置。 FieldA有数千个可能的值,而FieldB只有5个。我最好的是:

  1. 在每个记录上添加索引,即索引(A),索引(B)
  2. 仅在FieldA上添加索引
  3. 添加分组索引,即索引(A,B)

2 个答案:

答案 0 :(得分:0)

我建议您在字段

上使用复合索引
 index my_index_name on my_table(fieldA, fieldB)

在场地中使用fieldA或FieldB应该以特定的方式改变性能......但是最好的选择是首选

答案 1 :(得分:0)

If you are doing WHERE A=(constant) AND B=(constant), then INDEX(A,B) and INDEX(B,A) work equally well.

But... OR messes things up. < messes things up. IN messes things up. Etc, etc.

Short rule for building the "best" index for WHERE ... AND ...

  1. Gather up any columns with = (constant) first.
  2. Then you can add one more column involved in a range, etc.

Example: WHERE A < 123 AND B = 987 can benefit most from INDEX(B, A) in that order.

If you have WHERE A=333 in one query and WHERE B=777 in another (nothing AND'd), then you need two indexes, one (A) (or beginning with A), and a similar one for B. INDEX(B, A) will not work for both.

More tips.