mysql索引面试题

2025-10-22 10:25:20

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');

mysql索引面试题

2、在表中建立索引:

 create index idx_test03_c1234 on test03(c1,c2,c3,c4);

mysql索引面试题

3、我们创建了符合索引idx_test03_c1234,根据以下sql分析下索引使用情况。

explain select * from test03 where c1='a1' and c2='a2' and c3='a3' and c4='a4';

mysql索引面试题

4、explain select * from test03 where c1='a1' and c2='a2' and c3>'a3' and c4='a4';

这个sql语句的情况下值使用到了c1、c2索引,这个是因为范围之后的索引全部失效了。

mysql索引面试题

5、接下来看一条排序的sql。

explain select * from test03 where c1='a1' and c2='a2'  and c4='a4' order by c3;

这里索引c1和c2用来查找数据,c3索引用来排序。

mysql索引面试题

6、看一下这条sql。

explain select * from test03 where c1='a1' and c2='a2'   order by c4;

这条sql的使用了c1、c2索引查找,没有使用c4索引进行排序。

mysql索引面试题

7、接下来我们思考一下两个字段排序的情况有没有使用到索引。

mysql索引面试题

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢