你可能真的不知道的索引失效是怎么回事,你品,你细品?

目录

1、前提准备

 2、1全值匹配(最好)

 3、最佳左前缀法则

3、1要求

 注:判断哪个索引生效,查看key_len的具体值来确定

3、2跳过第一个,索引失效

3、3跳过前两个, 索引失效

3、4跳过中间一个 ,只有第一个生效

3、5顺序可以乱

 3、6不在索引列上做任何操作

 3、7范围条件右边的索引失效

 3、8mysql在使用不等于(!=或者<>)的时候无法使用索引会导致全表扫描

3、9 is not null 无法使用索引

3、10少用or 用or连接时, 会导致索引失效

3、11like以通配符开头(%qw)索引失效变成全表扫描 

3、12字符串不加引号索引失效

3、13尽量使用覆盖索引


1、前提准备

首先我们创建一个测试的员工表

create table employees
(
    id     int auto_increment
        primary key,
    name   varchar(20)    null,
    dep_id int            null,
    age    int            null,
    salary decimal(10, 2) null,
    cus_id int            null
);

其次我们创建一个复合索引

create index idx_name_age_sal on employees(name,age,salary);

效果图:

 2、1全值匹配(最好)

  1. 使用到了1个
    explain
    select * from employees where name = '李白';

  2. 使用到了2个
    explain
    select * from employees where name = '李白1' and age = 10;

  3. 使用用到了3个
    explain
    select * from employees where name = '李白1' and age = 10 and salary = 1000;

 3、最佳左前缀法则

3、1要求

如果索引的多列,要遵守最左前缀法则,指的就是从索引的最左列开始 并且不跳过索引中的列,如果左边的值未确定,那么无法使用此索引。

 注:判断哪个索引生效,查看key_len的具体值来确定

3、2跳过第一个,索引失效

explain
select * from employees where  age = 10 and salary = 1000;

3、3跳过前两个, 索引失效

explain
select * from employees where   salary = 1000;

3、4跳过中间一个 ,只有第一个生效

explain
select * from employees where name = '李白1'  and salary = 1000;

3、5顺序可以乱

explain
select * from employees where name = '李白1'  and salary = 1000 and age = 10;

 

 3、6不在索引列上做任何操作

计算,函数,类型转换,会导致索引失效而转向全表扫描

explain
select * from employees where trim(name) = '李白1' and age = 10 and salary = 1000;

 3、7范围条件右边的索引失效

explain
select * from employees where name = '李白1' and age > 10 and salary = 1000;

 3、8mysql在使用不等于(!=或者<>)的时候无法使用索引会导致全表扫描

注:前提是欲查询的where条件没有与之相匹配的

explain
select * from employees where name != '李白';

3、9 is not null 无法使用索引

explain
select * from employees where age  is not null ;

3、10少用or 用or连接时, 会导致索引失效

explain
select * from employees where name = '李白1' or age >10;

3、11like以通配符开头(%qw)索引失效变成全表扫描 

explain
select * from employees where name like '%李';

3、12字符串不加引号索引失效

explain
select * from employees where name = 200;

3、13尽量使用覆盖索引

explain
select * from employees where name = '李白1' and age = 10 and salary = 1000;

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的小绵羊

c币是什么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值