mysql调优
排序优化
-
消除using fileshort:
场景一:select id from table order by col1
为排序字段(col1)添加索引(索引本身是有序的)
场景二:select id form table order by col1,col2
错误的做法:给他们添加单列索引
正确的做法:给col1 和col2添加联合索引,顺序要跟排序order by后顺序一致
场景三:select id from table order by col1 asc,col2 desc
直接创建索引,默认都是升序,依然会using filesort
ALERT TABLE ta ADD INDEX idx_col1_col2(col1,col2)
解决方法是:创建索引的时候指定升降序(8版本才支持)
ALERT TABLE ta ADD INDEX idx_col1_col2(col1 asc,col2 desc)
以下sql是否能避免using filesort(idx_col1_col2(col1 ,col2 ,col3))
select id from table order by col2,col1,col3; 否
select id form table order by col1,col3; 否
一定要满足最左前缀原则
1 a x 1 a y 1 b x 1 b z 2 a y 2 a z 2 c x 2 c z select id from table where col1=100 order by col2
最好给col1 和 col2 加联合索引,条件不允许的情况下优先对col1添加索引,最大过滤数据
以下sql能不能避免using filesort:
select id from table where col1 in(100,102) order by col2; 否
select id from table where col1>=100 and col1<102 order by col2; 否
经过前面的条件筛选后排序字段都是无序的,只有col1 在具体等于某个值的情况下col2才是有序的。
场景四:select * from table order by col1,id limit 10000;
给col1添加索引后也不一定走索引排序,因为MySQL会考虑回表成本。
优化方式:
- order by 和select 字段加联合索引
- 采用手动回表的方式:
select a.* from table a inner join(select id from table order by col1,id limit 10000 )b on a.id=b.id;
mysql排序内存排序以及外部磁盘辅助进行排序,当sort buffer 一次装不下的情况下会写入文件,保证文件内部有序,然后采用归并算法让所有数据都有序。
排序方式:
- rowid排序(双路排序):将排序字段和rowid(主键)组成键值对存入sort buffer因为取值和回表需要两次操作磁盘所以叫双路排序,好处就是占用sort buffer 小,坏处就是要回表
例子:select col2 from table order by col1;
- 全字段排序:将排序的字段和需要返回的字段组成键值对,存入sort buffer,好处不需要回表,坏处占用sort buffer 多,更容易使用临时文件
- 打包全字段排序:全字段的改良,对查询字段进行压缩,以便于存放更多记录到sort buffer
sort_buffer_size:参数解释执行排序使用的缓冲大小
设置排序缓存命令:
查看参数值:show variable like ‘sort_buffer_size’;
修改参数的值:(session和global级别)
session sort_buffer_size = 1023*1024;
set global sort_buffer_size 1024*1024;
设置永久有效修改/etc/my.cnf
innodb_sort_buffer_size设置的是创建innodb索引时使用到的sort_buffer的大小,与排序无关。
max_length_for_sort_data:参数解释提供给用户控制排序算法的参数,8版本废除
返回列的总长度>max_length_for_sort_data ? rowid排序:全字段/打包全字段排序
查看参数值:show variables where variable_name ='max_length_for_sort_data'
默认1024字节
修改参数值:set max_length_for_sort_data=1024;
开优化器追踪命令
查看排序sql使用了哪种排序方式:optimizer trace
-
查询:
show variables where variable_name='optimizer_trace';
-
开启:
set optimizer_trace = ‘enable=on’;
-
控制最多展示多少结果:
set optimizer_trace_limit =5;
-
第一个要展示的optimizer_trace偏移量(默认1):
set optimizer_trace_offset=1;
-
执行排序sql
-
查询追踪信息:
select *from INFORMATION_SCHEMA.OPTIMIZER_TRACE;
子查询优化
案例:
select * from orders where id in (select order_id from order_details where product_code =“xxx”)
外层每一行都对子查询进行调用 select_type(DEPENDENT SUBQUERY),8版本后对子查询会进行优化,第一次子查询的结果保存为临时表,后续对子查询的访问直接通过临时表获得,整个过程中对子查询只需要执行一次。
优化sql:
select t1.* from orders t1 inner join order_details t2 on t1.id=t2.order_id where t2.prodict_code=‘xxx’
添加索引:
联合索引 ADD INDEX idx_pcode_oid(prodict_code,order_id)
总结:
- 使用表连接替代子查询,尤其是子查询的结果集较大
- 添加符合索引及逆行优化,其中字段包含were条件字段与关联字段
- 符合索引中字段的顺序要遵循最左前缀原则
- mysql8 自动对子查询进行优化,性能接近表连接
- 尽量做到小表驱动大表