分析SQL语句

‘’’
排序优化
分析
1.观察,至少跑一天,看看生产的慢SQL情况
2.开启慢查询日志,设置阙值,比如超过5秒钟的就是慢SQL,并抓取出来
3.explain + 慢SQL分析
4.show profile
5.进行SQL数据库服务器的参数调优(运维orDBA来做)

总结
1.慢查询的开启并捕获
2.explain+慢SQL分析
3.show profile查询SQL在MySQL服务器里面的执行细节
4.SQL数据库服务器的参数调优

永远小表驱动大表

for i in range(5):
for j in range(1000):
pass

for i in range(1000):
for j in range(5):
pass

order by优化
order by子句,尽量使用index方式排序,避免使用filesort方式排序

1.建表,插入测试数据

create table tbla(
age int,
birth timestamp not null
);

insert into tbla(age,birth) values(22,now());
insert into tbla(age,birth) values(23,now());
insert into tbla(age,birth) values(24,now());

2.建立索引

create index idx_tbla_agebrith on tbla(age,birth);

出现文件内排序using filesort 按建立索引的顺序排序为优
在这里插入图片描述
如果将>换成=,成固定值,不会出现内排序,可以组合
在这里插入图片描述
查询字段一个升序一个降序也会出现内排序using filesort,
查询时同时升序或降序避免using filesort
在这里插入图片描述

3.分析

MySQL支持两种方式的排序,filesort和index,index效率高,MySQL扫描索引本身完成排序。filesort方式效率较低

order by 满足两种情况下,会使用index方式排序
1.order by 语句使用索引最左前列
2.使用where子句与order by子句条件组合满足索引最左前列

filesort有两种算法-双路排序和单路排序
双路排序,MySQL4.1之前是使用双路排序,字面意思就是两次扫描磁盘,最终得到数据,读取行指针和order by列,对他们进行排序,
然后扫描已经排序好的列表,按照列表中的值重新从列表中读取对应的数据输出

单路排序,从磁盘读取查询需要的所有列,按照order by列在buffer对他们进行排序,然后扫描排序后的列表进行输出,
它的效率更快一些,避免了第二次读取数据,并且把随机IO变成了顺序IO,但是它会使用更多的空间

优化策略调整MySQL参数

增加sort_buffer_size参数设置
增大max_lenght_for_sort_data参数的设置
提高order by的速度
order by时select * 是一个大忌,只写需要的字段
当查询的字段大小总和小于max_length_for_sort_data而且排序字段不是text|blob类型时,会用改进后的算法–单路排序
两种算法的数据都有可能超出sort_buffer的容量,超出之后,会创建tmp文件进行合并排序,导致多次I/O
尝试提高sort_buffer_size
尝试提高max_length_for_sort_data

练习:
索引 a_b_c(a,b,c)

order by a,b (不会出现内排序using filesort)
order by a,b,c (不会出现内排序using filesort)
order by a desc,b desc,c desc (不会出现内排序using filesort)

where a = const order by b,c (不会出现内排序using filesort)
where a = const and b = const order by c (不会出现内排序)
where a = const and b > const order by b,c (不会出现内排序)
order by a asc,b desc,c desc (会出现内排序)
where g = const order by b,c (会出现内排序)
where a = const order by c (会出现内排序)
where a = const order by a,d (会出现内排序)
‘’’

发布了57 篇原创文章 · 获赞 0 · 访问量 929

猜你喜欢

转载自blog.csdn.net/weixin_45905671/article/details/104140671
今日推荐