示例表

  1. CREATE TABLE `employees` (
  2. `id` int(11) NOT NULL AUTO_INCREMENT,
  3. `name` varchar(24) NOT NULL DEFAULT '' COMMENT '姓名',
  4. `age` int(11) NOT NULL DEFAULT '0' COMMENT '年龄',
  5. `position` varchar(20) NOT NULL DEFAULT '' COMMENT '职位',
  6. `hire_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入职时间',
  7. PRIMARY KEY (`id`),
  8. KEY `idx_name_age_position` (`name`,`age`,`position`) USING BTREE
  9. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='员工记录表';
  10. INSERT INTO employees(name,age,position,hire_time) VALUES('LiLei',22,'manager',NOW());
  11. INSERT INTO employees(name,age,position,hire_time) VALUES('HanMeimei', 23,'dev',NOW());
  12. INSERT INTO employees(name,age,position,hire_time) VALUES('Lucy',23,'dev',NOW());
  13. ‐‐ 插入一些示例数据
  14. drop procedure if exists insert_emp;
  15. delimiter ;;
  16. create procedure insert_emp()
  17. begin
  18. declare i int;
  19. set i=1;
  20. while(i<=100000)do
  21. insert into employees(name,age,position) values(CONCAT('zhuge',i),i,'dev');
  22. set i=i+1;
  23. end while;
  24. end;;
  25. delimiter ;
  26. call insert_emp();

1、联合索引第一个字段用范围不会走索引

  1. EXPLAIN SELECT * FROM employees WHERE `name` > 'LiLei' AND age = 22 AND position ='manager';

image.png
2、强制走索引

  1. explain select * from employees force index(idx_name_age_position) where name > 'LiLei';

结论:虽然使用了强制走索引让联合索引第一个字段范围查找也走索引,扫描的行rows看上去也少了点,但是最终查找效率不一定比全表扫描高,因为回表效率不高

  1. set global query_cache_size=0;
  2. set global query_cache_type=0;
  3. explain select * from employees where name > 'LiLei';
  4. explain SELECT * FROM employees force index(idx_name_age_position) WHERE name > 'LiLei';

3、覆盖索引优化

  1. EXPLAIN SELECT name,age,position FROM employees WHERE name > 'LiLei' AND age = 22 AND position ='manager';

image.png
4、in和or在表数据量比较大的情况会走索引,在表记录不多的情况下会选择全表扫描

  1. EXPLAIN SELECT * FROM employees WHERE name in ('LiLei','HanMeimei','Lucy') AND age = 22 AND position ='manager';

image.png
5、like KK% 一般情况都会走索引

  1. EXPLAIN SELECT * FROM employees WHERE name like 'LiLei%' AND age = 22 AND position ='manager';

image.png
索引下推(Index Condition Pushdown,ICP), like KK%其实就是用到了索引下推优化什么是索引下推了?
可以在索引遍历过程中,对索引中包含的所有字段先做判断,过滤掉不符合条件的记录之后再回表,可以有效的减少回表次数。
为什么范围查找Mysql没有用索引下推优化?
估计应该是Mysql认为范围查找过滤的结果集过大,like KK% 在绝大多数情况来看,过滤后的结果集比较小,所以这里Mysql选择给 like
KK% 用了索引下推优化,当然这也不是绝对的,有时like KK% 也不一定就会走索引下推。

Mysql如何选择合适的索引

  1. EXPLAIN select * from employees where name > 'a';

image.png

  1. EXPLAIN select * from employees where name > 'zzz';

image.png
trace工具用法:

  1. set session optimizer_trace="enabled=on",end_markers_in_json=on; ‐‐开启trace
  2. select * from employees where name > 'a' order by position;
  3. SELECT * FROM information_schema.OPTIMIZER_TRACE;
  4. {
  5. "steps": [
  6. {
  7. "join_preparation": { --第一阶段:SQL准备阶段,格式化sql
  8. "select#": 1,
  9. "steps": [
  10. {
  11. "expanded_query": "/* select#1 */ select `employees`.`id` AS `id`,`employees`.`name` AS `name`,`employees`.`age` AS `age`,`employees`.`position` AS `position`,`employees`.`hire_time` AS `hire_time` from `employees` where (`employees`.`name` > 'a') order by `employees`.`position`"
  12. }
  13. ] /* steps */
  14. } /* join_preparation */
  15. },
  16. {
  17. "join_optimization": { --第二阶段:SQL优化阶段
  18. "select#": 1,
  19. "steps": [
  20. {
  21. "condition_processing": {
  22. "condition": "WHERE",
  23. "original_condition": "(`employees`.`name` > 'a')",
  24. "steps": [
  25. {
  26. "transformation": "equality_propagation",
  27. "resulting_condition": "(`employees`.`name` > 'a')"
  28. },
  29. {
  30. "transformation": "constant_propagation",
  31. "resulting_condition": "(`employees`.`name` > 'a')"
  32. },
  33. {
  34. "transformation": "trivial_condition_removal",
  35. "resulting_condition": "(`employees`.`name` > 'a')"
  36. }
  37. ] /* steps */
  38. } /* condition_processing */
  39. },
  40. {
  41. "substitute_generated_columns": {
  42. } /* substitute_generated_columns */
  43. },
  44. {
  45. "table_dependencies": [
  46. {
  47. "table": "`employees`",
  48. "row_may_be_null": false,
  49. "map_bit": 0,
  50. "depends_on_map_bits": [
  51. ] /* depends_on_map_bits */
  52. }
  53. ] /* table_dependencies */
  54. },
  55. {
  56. "ref_optimizer_key_uses": [
  57. ] /* ref_optimizer_key_uses */
  58. },
  59. {
  60. "rows_estimation": [ --预估表的访问成本
  61. {
  62. "table": "`employees`",
  63. "range_analysis": {
  64. "table_scan": { --全表扫描情况
  65. "rows": 94103, --扫描行数
  66. "cost": 19176 --查询成本
  67. } /* table_scan */,
  68. "potential_range_indexes": [ --查询可能使用的索引
  69. {
  70. "index": "PRIMARY", --主键索引
  71. "usable": false,
  72. "cause": "not_applicable"
  73. },
  74. {
  75. "index": "idx_name_age_position", --辅助索引
  76. "usable": true,
  77. "key_parts": [
  78. "name",
  79. "age",
  80. "position",
  81. "id"
  82. ] /* key_parts */
  83. }
  84. ] /* potential_range_indexes */,
  85. "setup_range_conditions": [
  86. ] /* setup_range_conditions */,
  87. "group_index_range": {
  88. "chosen": false,
  89. "cause": "not_group_by_or_distinct"
  90. } /* group_index_range */,
  91. "analyzing_range_alternatives": { --分析各个索引使用成本
  92. "range_scan_alternatives": [
  93. {
  94. "index": "idx_name_age_position",
  95. "ranges": [
  96. "a < name"
  97. ] /* ranges */,
  98. "index_dives_for_eq_ranges": true,
  99. "rowid_ordered": false,
  100. "using_mrr": false,
  101. "index_only": false, --是否使用覆盖索引
  102. "rows": 47051, --索引扫描行数
  103. "cost": 56462, --索引使用成本
  104. "chosen": false, --是否使用该索引
  105. "cause": "cost"
  106. }
  107. ] /* range_scan_alternatives */,
  108. "analyzing_roworder_intersect": {
  109. "usable": false,
  110. "cause": "too_few_roworder_scans"
  111. } /* analyzing_roworder_intersect */
  112. } /* analyzing_range_alternatives */
  113. } /* range_analysis */
  114. }
  115. ] /* rows_estimation */
  116. },
  117. {
  118. "considered_execution_plans": [
  119. {
  120. "plan_prefix": [
  121. ] /* plan_prefix */,
  122. "table": "`employees`",
  123. "best_access_path": { --最优访问路径
  124. "considered_access_paths": [ --最终选择访问路径
  125. {
  126. "rows_to_scan": 94103,
  127. "access_type": "scan", --访问类型:为scan,全表扫描
  128. "resulting_rows": 94103,
  129. "cost": 19174,
  130. "chosen": true, --确认
  131. "use_tmp_table": true
  132. }
  133. ] /* considered_access_paths */
  134. } /* best_access_path */,
  135. "condition_filtering_pct": 100,
  136. "rows_for_plan": 94103,
  137. "cost_for_plan": 19174,
  138. "sort_cost": 94103,
  139. "new_cost_for_plan": 113277,
  140. "chosen": true
  141. }
  142. ] /* considered_execution_plans */
  143. },
  144. {
  145. "attaching_conditions_to_tables": {
  146. "original_condition": "(`employees`.`name` > 'a')",
  147. "attached_conditions_computation": [
  148. ] /* attached_conditions_computation */,
  149. "attached_conditions_summary": [
  150. {
  151. "table": "`employees`",
  152. "attached": "(`employees`.`name` > 'a')"
  153. }
  154. ] /* attached_conditions_summary */
  155. } /* attaching_conditions_to_tables */
  156. },
  157. {
  158. "clause_processing": {
  159. "clause": "ORDER BY",
  160. "original_clause": "`employees`.`position`",
  161. "items": [
  162. {
  163. "item": "`employees`.`position`"
  164. }
  165. ] /* items */,
  166. "resulting_clause_is_simple": true,
  167. "resulting_clause": "`employees`.`position`"
  168. } /* clause_processing */
  169. },
  170. {
  171. "reconsidering_access_paths_for_index_ordering": {
  172. "clause": "ORDER BY",
  173. "index_order_summary": {
  174. "table": "`employees`",
  175. "index_provides_order": false,
  176. "order_direction": "undefined",
  177. "index": "unknown",
  178. "plan_changed": false
  179. } /* index_order_summary */
  180. } /* reconsidering_access_paths_for_index_ordering */
  181. },
  182. {
  183. "refine_plan": [
  184. {
  185. "table": "`employees`"
  186. }
  187. ] /* refine_plan */
  188. }
  189. ] /* steps */
  190. } /* join_optimization */
  191. },
  192. {
  193. "join_execution": { --第三阶段,SQL执行阶段
  194. "select#": 1,
  195. "steps": [
  196. {
  197. "filesort_information": [
  198. {
  199. "direction": "asc",
  200. "table": "`employees`",
  201. "field": "position"
  202. }
  203. ] /* filesort_information */,
  204. "filesort_priority_queue_optimization": {
  205. "usable": false,
  206. "cause": "not applicable (no LIMIT)"
  207. } /* filesort_priority_queue_optimization */,
  208. "filesort_execution": [
  209. ] /* filesort_execution */,
  210. "filesort_summary": { --文件排序信息
  211. "rows": 100000, --预计扫描行数
  212. "examined_rows": 100000, --参与排序的行
  213. "number_of_tmp_files": 30, --使用临时文件的个数,这个值如果为0代表全部使用sort_buffer内存排 --序,否则使用磁盘文件排序
  214. "sort_buffer_size": 262056, --排序缓存的大小,单位Byte
  215. "sort_mode": "<sort_key, packed_additional_fields>" --排序方式,这里使用单路排序
  216. } /* filesort_summary */
  217. }
  218. ] /* steps */
  219. } /* join_execution */
  220. }
  221. ] /* steps */
  222. }

常见sql深入优化

Order by与Group by优化

  1. EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' AND position ='manager' order by age;

image.png

  1. EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' order by position;

image.png

  1. EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' order by age,position;

image.png

  1. EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' order by position,age;

image.png

  1. EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' and age=22 order by position,age;

image.png

  1. EXPLAIN SELECT * FROM employees WHERE name in('LiLei','tong') order by age,position;

image.png

  1. EXPLAIN SELECT * FROM employees WHERE name > 'a' order by name;

image.png

  1. EXPLAIN SELECT name FROM employees WHERE name > 'a' order by name;

image.png

优化总结:

1、MySQL支持两种方式的排序filesort和index,Using index是指MySQL扫描索引本身完成排序。index
效率高,filesort效率低。
2、order by满足两种情况会使用Using index。
1) order by语句使用索引最左前列。
2) 使用where子句与order by子句条件列组合满足索引最左前列。
3、尽量在索引列上完成排序,遵循索引建立(索引创建的顺序)时的最左前缀法则。
4、如果order by的条件不在索引列上,就会产生Using filesort。
5、能用覆盖索引尽量用覆盖索引
6、group by与order by很类似,其实质是先排序后分组,遵照索引创建顺序的最左前缀法则。对于group
by的优化如果不需要排序的可以加上order by null禁止排序。注意,where高于having,能写在where中
的限定条件就不要去having限定了。

Using filesort文件排序原理详解

filesort文件排序方式

  • 单路排序:是一次性取出满足条件行的所有字段,然后在sort buffer中进行排序;用trace工具可以看到sort_mode信息里显示< sort_key, additional_fields >或者< sort_key, packed_additional_fields >
  • 双路排序(又叫回表排序模式):是首先根据相应的条件取出相应的排序字段可以直接定位行数据的行 ID,然后在 sort buffer 中进行排序,排序完后需要再次取回其它需要的字段;用trace工具可以看到sort_mode信息里显示< sort_key, rowid >

MySQL 通过比较系统变量 max_length_for_sort_data(默认1024字节) 的大小和需要查询的字段总大小来判断使用哪种排序模式。
如果 字段的总长度小于max_length_for_sort_data ,那么使用 单路排序模式;
如果 字段的总长度大于max_length_for_sort_data ,那么使用 双路排序模式。
我们先看单路排序的详细过程:
1. 从索引name找到第一个满足 name = ‘zhuge’ 条件的主键 id
2. 根据主键 id 取出整行,取出所有字段的值,存入 sort_buffer 中
3. 从索引name找到下一个满足 name = ‘zhuge’ 条件的主键 id
4. 重复步骤 2、3 直到不满足 name = ‘zhuge’
5. 对 sort_buffer 中的数据按照字段 position 进行排序
6. 返回结果给客户端
我们再看下双路排序的详细过程:
1. 从索引 name 找到第一个满足 name = ‘zhuge’ 的主键id
2. 根据主键 id 取出整行,把排序字段 position 和主键 id 这两个字段放到 sort buffer 中
3. 从索引 name 取下一个满足 name = ‘zhuge’ 记录的主键 id
4. 重复 3、4 直到不满足 name = ‘zhuge’
5. 对 sort_buffer 中的字段 position 和主键 id 按照字段 position 进行排序
6. 遍历排序好的 id 和字段 position,按照 id 的值回到原表中取出 所有字段的值返回给客户端
注意,如果全部使用sort_buffer内存排序一般情况下效率会高于磁盘文件排序,但不能因为这个就随便增大sort_buffer(默认1M),mysql很多参数设置都是做过优化的,不要轻易调整。

索引设计原则

1、代码先行,索引后上
一般应该等到主体业务功能开发完毕,把涉及到该表相关sql都要拿出来分析之后再建立索引。
2、联合索引尽量覆盖条件
比如可以设计一个或者两三个联合索引(尽量少建单值索引),让每一个联合索引都尽量去包含sql语句里的 where、order by、group by的字段,还要确保这些联合索引的字段顺序尽量满足sql查询的最左前缀原则。
3、不要在小基数字段上建立索引
索引基数是指这个字段在表里总共有多少个不同的值,比如一张表总共100万行记录,其中有个性别字段, 其值不是男就是女,那么该字段的基数就是2。如果对这种小基数字段建立索引的话,还不如全表扫描了,因为你的索引树里就包含男和女两种值,根本没法进行快速的二分查找,那用索引就没有太大的意义。
一般建立索引,尽量使用那些基数比较大的字段,就是值比较多的字段,那么才能发挥出B+树快速二分查找的优势来。
4、长字符串我们可以采用前缀索引
对于这种varchar(255)的大字段可能会比较占用磁盘空间,可以稍微优化下,比如针对这个字段的前20个字符建立索引,就是说,对这个字段里的每个值的前20个字符放在索引树里,类似于 KEY index(name(20),age,position)。
此时你在where条件里搜索的时候,如果是根据name字段来搜索,那么此时就会先到索引树里根据name字段的前20个字符去搜索,定位到之后前20个字符的前缀匹配的部分数据之后,再回到聚簇索引提取出来完整的name字段值进行比对。
但是假如你要是order by name,那么此时你的name因为在索引树里仅仅包含了前20个字符,所以这个排序是没法用上索引的, group by也是同理。所以这里大家要对前缀索引有一个了解。
5、where与order by冲突时优先where
一般这种时候往往都是让where条件去使用索引来快速筛选出来一部分指定的数据,接着再进行排序。
因为大多数情况基于索引进行where筛选往往可以最快速度筛选出你要的少部分数据,然后做排序的成本可能会小很多。
6、基于慢sql查询做优化
可以根据监控后台的一些慢sql,针对这些慢sql查询做特定的索引优化。
关于慢sql查询不清楚的可以参考这篇文章:https://blog.csdn.net/qq_40884473/article/details/89455740