mysql索引面试题
1、准备如下sql语句:
create table test03(
id int primary key not null auto_increment,
c1 char(10),
c2 char(10),
c3 char(10),
c4 char(10),
c5 char(10)
);
insert into test03(c1,c2,c3,c4,c5) value('a1','a2','a3','a4','a5');
insert into test03(c1,c2,c3,c4,c5) value('b1','b2','b3','b4','b5');
insert into test03(c1,c2,c3,c4,c5) value('c1','c2','c3','c4','c5');
insert into test03(c1,c2,c3,c4,c5) value('d1','d2','d3','d4','d5');
insert into test03(c1,c2,c3,c4,c5) value('e1','e2','e3','e4','e5');
2、在表中建立索引:
create index idx_test03_c1234 on test03(c1,c2,c3,c4);
3、我们创建了符合索引idx_test03_c1234,根据以下sql分析下索引使用情况。
explain select * from test03 where c1='a1' and c2='a2' and c3='a3' and c4='a4';
4、explain select * from test03 where c1='a1' and c2='a2' and c3>'a3' and c4='a4';
这个sql语句的情况下值使用到了c1、c2索引,这个是因为范围之后的索引全部失效了。
5、接下来看一条排序的sql。
explain select * from test03 where c1='a1' and c2='a2' and c4='a4' order by c3;
这里索引c1和c2用来查找数据,c3索引用来排序。
6、看一下这条sql。
explain select * from test03 where c1='a1' and c2='a2' order by c4;
这条sql的使用了c1、c2索引查找,没有使用c4索引进行排序。
7、接下来我们思考一下两个字段排序的情况有没有使用到索引。