一旦建立索引,select 查询语句的where条件要尽量符合最佳左前缀的原则,如若能做到全值匹配最好。
索引优化的第一个前提就是建好索引,第二个就是避免索引失效
索引失效的场景
小总结:
假设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 = 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 |
是什么:是mysql提供可以用来分析当前会话中语句执行的资源消耗情况。可以用于sql的调优的测量
官网介绍:
默认情况下,参数处于关闭状态,开启后默认保存最近15次的运行结果
1.是否支持,看看当前的mysql版本是否支持
show variables like 'profiling';
2.开启功能,默认是关闭,使用前需要开启
set profiling=on;
3.运行sql
select * from emp group by id%10 limit 150000; select * from emp group by id%20 order by 5
4.查看结果 show profile;
5.诊断sql,show profile cpu,block io for query 上一步前面的问题sql数字号码;
status | 建议 |
---|---|
system lock | 确认是由于哪个锁引起的,通常是因为mysql或innodb内核级的锁引起的建议:如果耗时较大再关注即可,一般情况下都还好 |
sending data | 从server端发送数据到客户端,也有可能是接收存储引擎层返回的数据,再发送给客户端,数据量很大时尤其经常能看见备注:sending data不是网络发送,是从硬盘读取,发送到网络是writing to net建议:通过索引或加上limit,减少需要扫描并且发送给客户端的数据量 |
sorting result | 正在对结果进行排序,类似creating sort index,不过是正常表,而不是在内存表中进行排序建议:创建适当的索引 |
table lock | 表级锁,没什么好说的,要么是因为myisam引擎表级锁,要么是其他情况显式锁表 |
create sort index | 当前的select中需要用到临时表在进行order by排序建议:创建适当的索引 |
checking query cache for querychecking privileges on cachedsending cached result to clienstoring result in query cache | 和query cache相关的状态,已经多次强烈建议关闭 |
6. 日常开发需要注意的结论
示例:剖析 select * from emp group by id%20 order by 5
由剖析报告看出,其中 copying to tmp table 步骤花费了大量的时间,所以这条sql应该优化了。
注:该文的sql只是为了便利的梳理知识点使用,不需要关心这条sql为什么这样写,了解以上知识的使用方法就可以啦
如对本文有疑问, 点击进行留言回复!!
第三次学JAVA再学不好就吃翔(part88)--ArrayList嵌套ArrayList
使用ffmpeg视频切片并加密和视频AES-128加密后播放
JAVA程序设计:最长重复子串(LeetCode:1044)
LiveGBS国标GB/T28181云端录像分布式录像存储自动清理时移回看录像下载播放
网友评论