mysql的一些优化

前言 : SQL优化,是一种概率层面的优化。至于是否实际使用了我们的优化,需要通过explain进行推测。
注意:服务层中有SQL优化器,可能会影响我们的优化,同时注明:sql的优化前提是有索引!有索引!有索引!

● in和exists的使用场景
select * from A where id exists (select * from B)

exist语法:
将主查询(A)的结果,放到子查询(B)结果中进行条件校验(看子查询是否有数据,如果有数据则校验成功) ,
如果符合校验,则保留数据;也就是说A的数据越少越好.so,exists适合主查询为小表,子查询为大表;

结论:
如果主查询的数据集大,则使用in,效率高.
如果子查询的数据集大,则使用exists,效率高。

● like尽量以’常量’开头,不要以"%"开头,否则索引失效
I: select * from A where name like '%h%' ; name索引失效(explain查看)
II: 如果必须使用like '%xx%'进行模糊查询,可以使用索引覆盖,挽救一部分; select name from A where name like '%x%' ;

● 复合索引
1.不要跨列使用或者无序使用,遵循最佳左前缀
如 index_a_b(a,b) ; select * from A where b = 1 and a = 10 ---索引无效,索引顺序有误
select * from A where b = 1 ---索引失效,跨列使用

2.尽量使用全索引匹配
select * from A where a = 1 and b = 5 ;

● 不要在索引上进行任何操作(计算,转换,函数),否则索引失效
1.select * from A where a * 3 = 6 ; ---索引失效

2.注意:如果查询的是字符串.一定得加''或者"",否则会转换造成索引失效(查询数字使用字符串同理)
select * from A where a = '6' ---索引失效,使用了转换

3.对于复合索引,如果左边失效,那么右侧全部失效

4.复合索引不能使用不等于(!=,<>) 或 is null (is not null) ,否则自身以及右侧全部失效.复合索引如果有>,则自身和右侧索引全部失效

● 尽量使用索引覆盖(using index)
inde_a_b_c(a,b,c) ; select a,b,c from A where a = x and b = x;

● 尽量不要使用类型转换(显示,隐式),否则索引失效
select * from A where name = 'ws' ;
select * from A where name = 123 ; 底层将123->"123",进行了类型转换,索引失效

● 尽量不使用or,否则索引失效
select * from A where a = 1 or id = 1 ; 造成or左侧的索引失效

猜你喜欢

转载自blog.csdn.net/bb23417274/article/details/84763252