1. CREATE TABLE `employees_copy` (
  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();

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

执行语句

mysql> explain select * from employees where name > ‘LiLei’ and age = 22 and position = ‘manager’;
image.png
执行计划,俺条件来说name可以走索引,但是mysql底层做了分析,走全表速度可能会更快。

image.png
可以用覆盖索引解决上面没走索引的问题(覆盖索引:不是真正的索引,只是一种查询方式,查询的结果字段在索引树里面全包含了。类似于type字段里面的index查询,就是索引树里面用到了所有的索引进行查询。不需要回表。)

强制走索引

explain select * from employees force index(idx_name_age_position) where name>’LiLei%’ and age = 22 and position = ‘manager’;
image.png

覆盖索引优化

explain select name,age,position from employees where name > ‘LiLei’ and age = 22 and position = ‘manager’;
image.png

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

1:explain select from employees where name in(‘LiLei%’,’HanMeimei’,’Lucy’) and age = 22 and position = ‘manager’;
2:explain select
from employees where (name=’LiLei%’ or name=’HanMeimei’) and age = 22 and position = ‘manager’;
两个都走索引了
image.png

3:explain select from employees_copy where name in(‘LiLei%’,’HanMeimei’,’Lucy’) and age = 22 and position = ‘manager’;
4: explain select
from employees_copy where (name=’LiLei%’ or name=’HanMeimei’) and age = 22 and position = ‘manager’;
当前两个都没有走索引,因为数据量比较少
image.png

like KK% 一般情况都会走索引

explain select from employees where name > ‘LiLei’ and age = 22 and position = ‘manager’;
explain select
from employees where name like ‘LiLei%’ and age = 22 and position = ‘manager’;
image.png
第一个没走索引,第二个走索引。
查询语句中>当作范围
查询语句中like当作常量(in)
explain select from employees where name like ‘LiLei%’ and age = 22 and position = ‘manager’;
explain select
from employees_copy where name like ‘LiLei%’ and age = 22 and position = ‘manager’;
image.png
当前两条语句都会用到索引,和数据量多少没关系

mysql5.6之前,联合索引的时候,先从二级索引查询第一个索引,根据查询到的id,去聚簇索引中查询数据,然后再返回二级索引继续查询剩下的条件。5.6之后加入新的概念,索引下推。
索引下推:like KK%就是用到了索引下推,mysql5.6之后的新功能,联合索引的时候,先查询第一个条件,第一个条件符合的情况下,再在当前二级索引里面过滤剩下条件,比5.6之前版本少了回表的操作,过滤的结果集少了。只会看当前联合索引中的其它字段,找到的结果集更少,然后根据过滤后的id去聚簇索引树中查找。
>不走索引下推,

mysql如何选择合适的索引

explain select from employees where name > ‘a’;
explain select
from employees where name > ‘zzz’;
image.png
上面两条语句执行结果,第一个没有走索引,第二个走索引了???通过trance工具查看

trance:

因为trance工具影响mysql性能,所以用完之后需要关闭
trance使用:

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

常见sql优化

order by:

EXPLAIN SELECT * FROM employees WHERE name = ‘LiLei’ AND position = ‘dev’ ORDER BY age;
结果分析:order by 会走索引,name肯定走索引,order by走索引不会提现在字段长度上面。Using filesort就是没有用到索引,但是没有filesort。
image.png
explain select * from employees where name = ‘LiLei’ order by position;
结果分析:len = 74,用到了那么索引,但是后面用到position进行了排序,跳过age,所以出现Using filesort
image.png
explain select * from employees where name = ‘LiLei’ order by age,position;
结果分析:没有用到Using filesort,索引值用到了name,没有跳过age
image.png
explain select * from employees where name = ‘LiLei’ order by position,age;
结果分析:和上面一样,但是order by的顺序变了,出现了Using filesort,因为创建索引的顺序数name、age、position,排序的时候age和position的顺序颠倒了。
image.png
explain select * from employees where name = ‘LiLei’ and age = 20 order by position,age;
结果分析:Extra中并未出现Using filesort,因为age为常量,在排序中呗优化,所以索引未颠倒,不会出啊先Using filesort。
image.png
explain select * from employees where name = ‘LiLei’ order by age asc,position desc;
结果分析:虽然排序的字段列与索引顺序一样,且order by默认升序,这里position desc变成了降序,导致与索引的排序方式不同,从而产生Using filesort。Mysql8以上版本有降序索引可以支持该种查询方式。
image.png
explain select * from employees where name in(‘LiLei’,’zhuge’) order by age,position;
结果分析:对于排序来说,多个相等条件也是范围查询
image.png
explain select * from employees where name > ‘a’ order by name;
结果分析:用到了Using filesort,范围查找可能查询全部数据更快
image.png
优化方式:使用覆盖索引
explain select name,age,position from employees where name > ‘a’ order by name;
image.png

优化总结:

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

Using 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 ,那么使用 双路排序模·式。

索引设计原则:

代码先上,索引后上

  • 主题业务功能开发完毕后,再根据设计该表的sql分析再建索引

联合索引尽量覆盖条件

不要再小基数字段上建立索引

  • 譬如性别等。

长字符串我们可以采用前缀索引

  • 字段比较大,字节比较多,占用空间会比较大,可以优化,使用前缀索引。

where与order by冲突时优先where

基于慢sql查询做优化

索引设计实战


CREATE TABLE `employees_copy` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(24) NOT NULL DEFAULT '' COMMENT '姓名',
`age` int(11) NOT NULL DEFAULT '0' COMMENT '年龄',
`position` varchar(20) NOT NULL DEFAULT '' COMMENT '职位',
`hire_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入职时间',
PRIMARY KEY (`id`),
KEY `idx_name_age_position` (`name`,`age`,`position`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='员工记录表';

 INSERT INTO employees_copy(name,age,position,hire_time) VALUES('LiLei',22,'manager',NOW());
 INSERT INTO employees_copy(name,age,position,hire_time) VALUES('HanMeimei', 23,'dev',NOW());
 INSERT INTO employees_copy(name,age,position,hire_time) VALUES('Lucy',23,'dev',NOW());

 ‐‐ 插入一些示例数据
 drop procedure if exists insert_emp;
 delimiter ;;
 create procedure insert_emp()
 begin
 declare i int;
 set i=1;
 while(i<=100000)do
 insert into employees(name,age,position) values(CONCAT('zhuge',i),i,'dev');
 set i=i+1;
 end while;
 end;;
 delimiter ;
 call insert_emp();


select count(1) from employees;

SELECT COUNT(*) FROM employees;

set session optimizer_trace="enabled=on",end_markers_in_json=on; 

select * from employees where name > 'a' order by position; 
SELECT * FROM information_schema.OPTIMIZER_TRACE; 


EXPLAIN SELECT * FROM employees WHERE name = 'LiLei' AND position = 'dev' ORDER BY age;


EXPLAIN SELECT * FROM employees WHERE name in ('LiLei','zhuge')  ORDER BY age, position;

explain select * from employees where name = 'LiLei' order by position;


explain select * from employees where name = 'LiLei' order by age,position;

explain select * from employees where name = 'LiLei' order by position,age;

explain select * from employees where name = 'LiLei' and age = 20 order by position,age;

explain select * from employees where name = 'LiLei' order by age asc,position desc;

explain select * from employees where name in('LiLei','zhuge') order by age,position;

explain select name,age,position from employees where name > 'a' order by name;