上一篇 <<<MySQL性能优化之in、exists优化
下一篇 >>>MySQL如何性能优化面试题完美解答
1.Mysql排序支持两种filesort和index
1.1 using index
1.2 using filesort
2.Order by排序代码示例
2.1 查询条件和order by字段均被索引覆盖
explain select * from employees where name= 'jarye' and position ='ceo' order by age;
2.2 跳过联合索引中间值,出现了Using filesort
explain select * from employees where name= 'jarye' order by position;
2.3 索引顺序打乱,出现了Using filesort
explain select * from employees where name= 'jarye' order by position,age;
2.4 索引默认顺序排列,如果不一致,则会出现Using filesort
explain select * from employees where name= 'jarye' order by age asc ,position desc ;
explain select * from employees where name= 'jarye' order by age asc ,position asc ;
2.5 多个相等条件也是范围查询,也会出现Using filesort
explain select * from employees where name in('raby','jarye') order by age, position;
3.filesort实现原理
3.1单路排序步骤
3.2双路排序步骤
3.3单路和双路排序方式的选择及优缺点
4.单双路排序验证方式
-- 设置开启
set optimizer_trace='enabled=on',end_markers_in_json=on;
-- 以下两条语句同时执行,可查看sql语句的执行分析情况
select * from employees where name > 'jarye' ;
select * from information_schema.optimizer_trace;
--关闭trace
set session optimizer_trace="enabled=off";
"join_preparation": --第一阶段:SQl准备阶段
"join_optimization": --第二阶段:SQL优化阶段
"rows_estimation": [ --预估标的访问成本
{
"table": "`employees`",
"range_analysis": { --全表扫描情况
"table_scan": {
"rows": 68511, --扫描行数
"cost": 13929 --查询成本
} /* table_scan */,
"potential_range_indexes": [ --查询可能使用的索引
{
"index": "PRIMARY", --主键索引
"usable": false,
"cause": "not_applicable"
},
{
"index": "idx_name_age_position", --辅助索引
……
"analyzing_range_alternatives": { ‐‐分析各个索引使用成本
"range_scan_alternatives": [
{
"index": "idx_name_age_position",
"ranges": [
"mayikt < name"
] /* ranges */,
"index_dives_for_eq_ranges": true,
"rowid_ordered": false,
"using_mrr": false,
"index_only": false,
"rows": 34255, --‐‐索引扫描行数
"cost": 41107, --索引使用成本
"chosen": false, ‐‐是否选择该索引
"cause": "cost"
}
"join_execution": --第三阶段:SQL执行阶段
单路排序:
用trace工具可以看到sort_mode信息里显示< sort_key, additional_fields >或者< sort_key, packed_additional_fields >;
双路排序(回表查询):
用trace工具可以看到sort_mode信息里显示< sort_key, rowid >;
推荐阅读:
<<<MySQL执行计划示例解读
<<<MySQL性能优化之慢查询定位
<<<MySQL性能优化之表设计优化
<<<MySQL性能优化之常用SQL语句优化
<<<MySQL性能优化之索引调优实战
<<<MySQL性能优化之分页查询优化
<<<MySQL性能优化之关联查询优化
<<<MySQL性能优化之in、exists优化
<<<MySQL如何性能优化面试题完美解答