如果or前后连接的是同一个字段,那索引不会失效;如果是不同的字段,索引会失效
索引失效:
select * from user where name="xiaoming" or age=22;
索引不失效:
select * from user where name="xiaoming" or name="lihong";
like查询以%开头,会导致索引失效
select * from user where name like "%梅";
但是如果是不是以%开头,不会导致索引失效,以下情况索引生效:
select * from user where name like "李%";
也可以利用覆盖索引来命中索引:
select * from user where name like "%李%";
会导致全表扫描
如果在user表中,user_id的类型设置成了varchar(30),但是在sql语句中设置为其他类型值,不会命中索引:
select * from user where user_id=12;
如果索引有多列,要遵循最左前缀法则,即查询从最左列开始且不跳过索引中的列
比如,创建了一个联合索引(k1,k2,k3),相当于创建了(k1)、(k1,k2)、(k1、k2、k3)三个索引
下面的语句都不会命中索引:
select * from user where k2=1;
select * from user where k3=3;
select * from user where k2=2 and k3=3;
select * from user where k1=1 and k3=3;
下面的语句可以命中索引:
select * from user where k1=1;
select * from user where k1=1 and k2=2;
select * from user where k1=1 and k2=2 and k3=3;
select 8 from user where k2=2 and k3=3 and k1=1; //因为mysql的底层会帮我们做一个优化,它会把你的SQL优化为它认为一个效率最高的样子进行执行,所以这样子也不会失效
select * from user where DATE_ADD(login_time,INTERVAL 1 DAY)=7;
以下sql语句,索引失效:
select * from user where age + 1=30;
索引不失效:
select * from user where age=30 - 1;
not in、not exists导致索引失效
order by不走索引