MySQL中索引的使用细节

1. 全值匹配

条件字段使用“=”

2. 范围匹配(<= >= between and)

3. 独立的列

是指索引列不能是表达式的一部分,也不能是函数的参数

注意:要求索引的列必须是独立的一列才能用到索引。

4. 左值匹配

在使用like(模糊匹配)的时候,在左边没有通配符的情况下,才可以使用索引。

在mysql里,以%开头的like查询,用不到索引。

比如:根据歌词搜索歌曲的名称,根据剧情搜索电影的名称。sphinx来完成。

5. or运算都有索引

如果出现OR(或者)运算,要求所有参与运算的字段都存在索引,才会使用到索引。

6. 多列索引

对于创建的多列(复合)索引,只要查询条件使用了最左边的列,索引一般就会被使用。

因为联合索引是需要按顺序执行的,比如c1234组合索引,要想在c2上使用索引,必须先在c1上使用索引,要想在c3上使用索引,必须先在c2上使用索引,依此。

假设某个表有一个联合索引(c1,c2,c3,c4)

A where c1=x and c2=x and c4>x and c3=x
B where c1=x and c2=x and c4=x order by c3
C where c1=x and c4= x group by c3,c2
D where c1=x and c5=x order by c2,c3
E where c1=x and c2=x and c5=? order by c2,c3

分析下面A-E能否可以使用索引,该表插入的数据:

create table t4 (
    c1 tinyint(1) not null default 0,
    c2 tinyint(1) not null default 0,
    c3 tinyint(1) not null default 0,
    c4 tinyint(1) not null default 0,
    c5 tinyint(1) not null default 0,
    index c1234(c1,c2,c3,c4)
);

insert into t4 values (1,3,5,6,7),(2,3,9,8,3),(4,3,2,7,5);

分析:对name和age和email分别建立独立索引:最终只能使用到一个索引。

如果对name和age和email 建立了联合索引,在按照建立索引的顺序使用时,都用到了索引。

结论:如果有多个条件经常出现在where条件中,则可以对条件字段建立联合索引。

应用:比如goods表里面,cat_id和价格,就可以建立一个联合索引。

7. 当取出的数据量超过表中数据的20%,优化器就不会使用索引,而是全表扫描。

原文地址:https://www.cnblogs.com/chenjiacheng/p/6522254.html