mysql单列索引和联合索引

引用自:https://my.oschina.net/857359351/blog/658668

第一张表gift和索引为联合索引,如图:

第二张表gift2为单列索引,如图:

下面开始进行测试:

相同的SQL分别查询两张表,使用EXPLAIN解析一下SQL 

  select * from gift  where name = '道具' and scene_type=1;  

  select * from gift2 where name=‘道具’ and scene_type=1;

     显示的结果为两条SQL都会使用到索引,这我就不上图了。

然后只查询其中的某列,但是这个列已经创建索引 

  select name,status from gift  where name = '道具' and scene_type=1; 

  select name,status from gift2 where name=‘道具’ and scene_type=1;

    显示的结果为两条SQL也都使用了索引。

继续查询没有创建索引的列,这里rank字段并没有创建索引 

  select name,status,rank from gift  where name = '道具' and scene_type=1; 

  select name,status,rank from gift2 where name=‘道具’ and scene_type=1;

     显示的结果为两条SQL也都使用了索引。

接下来把SQL调整一下,name字段都建立了索引,下面把where条件里的name条件去掉 

  select name,status from gift  where scene_type=1; 

  select name,status from gift2 where scene_type=1;

     显示的结果为两条SQL也都使用了索引。

  select name,status,rank from gift  where scene_type=1;

  select name,status,rank from gift2 where scene_type=1;

   第一条SQL根本没有用到索引,第二条SQL还和以前一样,同样使用到了索引。

  其实在联合索引上会有一个mysql索引最左匹配原则,但是如果联合索引的第一个列不在where条件语句中,并且所查询的列其中有的是没有建立索引的,那么这个联合索引就是无效的,而且公司DBA也建议如果使用联合索引,那么where条件也要尽量根据联合索引的顺序来,如果不按照顺序来,索引也同样会用到,但是在执行前,SQL优化器也会将条件调整为联合索引的顺序,既然可以直接避免这种情况,就没必要再让SQL优化器去处理,毕竟处理也是有开销的。

猜你喜欢

转载自www.cnblogs.com/maxigang/p/9288908.html