以下属于MySQL主要的索引_MySQL高级 第8章单表使用索引常见的索引失效

1.全值匹配我最爱

1.1 有以下SQL语句

857d485794c103a5a911724b9e9c9ea3.png

4a81c146593846729ef5b5f6757a0a47.png

4ae3efbeb9d65bdc41b0ca697ff33088.png

3. 不要在索引列上做任何计算

不在索引列上做任何操作(计算、函数、(自动or手动)类型转换),会导致索引失效而转向全表扫描。

3.1 在查询列上使用了函数

EXPLAIN SELECT SQL_NO_CACHE * FROM emp WHERE age=30;

EXPLAIN SELECT SQL_NO_CACHE * FROM emp WHERE LEFT(age,3)=30;

a905eb7be46e8835f88ed0d5fb447f25.png

3.2在查询列上做了转换

create index idx_name on emp(name);

explain select sql_no_cache * from emp where name=’30000′;

explain select sql_no_cache * from emp where name=30000;

字符串不加单引号,则会在name列上做一次转换!

0461fece044708bbe93fdb73131fe3a9.png

4.索引列上不能有范围查询

explain SELECT SQL_NO_CACHE * FROM emp WHERE emp.age=30 and deptid=5 AND emp.name = ‘abcd’;

explain SELECT SQL_NO_CACHE * FROM emp WHERE emp.age=30 and deptid<=5 AND emp.name = ‘abcd’;

90d92177c72a673a8b086e81de527a25.png

5. 尽量使用覆盖索引

即查询列和索引列一直,不要写select *!

explain  SELECT SQL_NO_CACHE * FROM emp WHERE emp.age=30  and deptId=4 and name=’XamgXt’;

explain  SELECT SQL_NO_CACHE age,deptId,name  FROM emp WHERE emp.age=30  and deptId=4 and name=’XamgXt’;

d0bf1c876554d838c3cabb9859e532de.png

7.字段的is not null 和 is null

1003a3af18c07bdc8bc0b6a2d3959e8a.png

becc8621e762e633d7936754b606134d.png

8.like的前后模糊匹配

6b5a0cc46361cd697c6f3cad5055c1d4.png

47840db12ef6de749eb47fbfb9cffd75.png

10. 练习

假设index(a,b,c);

Where语句

索引是否被使用

where a = 3

Y,使用到a

where a = 3 and b = 5

Y,使用到a,b

where a = 3 and b = 5 and c = 4

Y,使用到a,b,c

where b = 3 或者 where b = 3 and c = 4  或者 where c = 4

N

where a = 3 and c = 5

使用到a, 但是c不可以,b中间断了

where a = 3 and b > 4 and c = 5

使用到a和b, c不能用在范围之后,b断了

where a is null and b is not null

is null 支持索引 但是is not null 不支持,所以 a 可以使用索引,但是  b不可以使用

where a <> 3

不能使用索引

where   abs(a) =3

不能使用 索引

where a = 3 and b like ‘kk%’ and c = 4

Y,使用到a,b,c

where a = 3 and b like ‘%kk’ and c = 4

Y,只用到a

where a = 3 and b like ‘%kk%’ and c = 4

Y,只用到a

where a = 3 and b like ‘k%kk%’ and c = 4

Y,使用到a,b,c

11. 口诀

全职匹配我最爱,最左前缀要遵守;

带头大哥不能死,中间兄弟不能断;

索引列上少计算,范围之后全失效;

LIKE百分写最右,覆盖索引不写*;

不等空值还有OR,索引影响要注意;

VAR引号不可丢,SQL优化有诀窍。

上一篇: MySQL高级 第7章批量数据脚本

下一篇: MySQL高级 第9章关联查询优化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值