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(name,age,position,hire_time) VALUES('LiLei',22,'manager',NOW());INSERT INTO employees(name,age,position,hire_time) VALUES('HanMeimei', 23,'dev',NOW());INSERT INTO employees(name,age,position,hire_time) VALUES('Lucy',23,'dev',NOW());‐‐ 插入一些示例数据drop procedure if exists insert_emp;delimiter ;;create procedure insert_emp()begindeclare i int;set i=1;while(i<=100000)doinsert into employees(name,age,position) values(CONCAT('zhuge',i),i,'dev');set i=i+1;end while;end;;delimiter ;call insert_emp();
联合索引第一个字段用范围不会走索引
执行语句
mysql> explain select * from employees where name > ‘LiLei’ and age = 22 and position = ‘manager’;![]() 执行计划,俺条件来说name可以走索引,但是mysql底层做了分析,走全表速度可能会更快。 ![]() 可以用覆盖索引解决上面没走索引的问题(覆盖索引:不是真正的索引,只是一种查询方式,查询的结果字段在索引树里面全包含了。类似于type字段里面的index查询,就是索引树里面用到了所有的索引进行查询。不需要回表。) |
|---|
强制走索引
explain select * from employees force index(idx_name_age_position) where name>’LiLei%’ and age = 22 and position = ‘manager’;![]() |
|---|
覆盖索引优化
explain select name,age,position from employees where name > ‘LiLei’ and age = 22 and position = ‘manager’;![]() |
|---|
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’; 两个都走索引了 ![]() 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’; 当前两个都没有走索引,因为数据量比较少 ![]() |
|---|
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’; ![]() 第一个没走索引,第二个走索引。 查询语句中>当作范围 查询语句中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’; ![]() 当前两条语句都会用到索引,和数据量多少没关系 |
|---|
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’; ![]() 上面两条语句执行结果,第一个没有走索引,第二个走索引了???通过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; |
|---|
{"steps": [{"join_preparation": { //第一阶段,格式化sql"select#": 1,"steps": [{"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`"}] /* steps */} /* join_preparation */},{"join_optimization": { //第二阶段:sql优化,譬如联合索引的时候,写的顺序不对,第二阶段会帮忙调整索引顺序进行优化。"select#": 1,"steps": [{"condition_processing": {"condition": "WHERE","original_condition": "(`employees`.`name` > 'a')","steps": [{"transformation": "equality_propagation","resulting_condition": "(`employees`.`name` > 'a')"},{"transformation": "constant_propagation","resulting_condition": "(`employees`.`name` > 'a')"},{"transformation": "trivial_condition_removal","resulting_condition": "(`employees`.`name` > 'a')"}] /* steps */} /* condition_processing */},{"substitute_generated_columns": {} /* substitute_generated_columns */},{"table_dependencies": [{"table": "`employees`","row_may_be_null": false,"map_bit": 0,"depends_on_map_bits": [] /* depends_on_map_bits */}] /* table_dependencies */},{"ref_optimizer_key_uses": [] /* ref_optimizer_key_uses */},{"rows_estimation": [ //预估表的访问成本{"table": "`employees`","range_analysis": {"table_scan": { //全表扫描的情况"rows": 100145, //扫描的行数"cost": 20384 //查询成本} /* table_scan */,"potential_range_indexes": [ //查询可能使用到的索引{"index": "PRIMARY", //主键索引"usable": false, //false为不用主键索引"cause": "not_applicable"},{"index": "idx_name_age_position", //二级索引(辅助索引)"usable": true,"key_parts": ["name","age","position","id"] /* key_parts */},{"index": "idx_hire_time","usable": false,"cause": "not_applicable"}] /* potential_range_indexes */,"setup_range_conditions": [] /* setup_range_conditions */,"group_index_range": {"chosen": false,"cause": "not_group_by_or_distinct"} /* group_index_range */,"analyzing_range_alternatives": {//分析各个索引使用的成本"range_scan_alternatives": [{"index": "idx_name_age_position","ranges": ["a < name" //索引使用范围] /* ranges */,"index_dives_for_eq_ranges": true,"rowid_ordered": false,"using_mrr": false,"index_only": false,"rows": 50072, //索引扫描行数"cost": 60087, //查询成本"chosen": false, //是否选择该索引"cause": "cost"}] /* range_scan_alternatives */,"analyzing_roworder_intersect": {"usable": false,"cause": "too_few_roworder_scans"} /* analyzing_roworder_intersect */} /* analyzing_range_alternatives */} /* range_analysis */}] /* rows_estimation */},{"considered_execution_plans": [ //考虑{"plan_prefix": [] /* plan_prefix */,"table": "`employees`","best_access_path": { //最优访问路径"considered_access_paths": [{"rows_to_scan": 100145,"access_type": "scan", //访问类型为scan,为全表臊面"resulting_rows": 100145,"cost": 20382,"chosen": true, //确定选择"use_tmp_table": true}] /* considered_access_paths */} /* best_access_path */,"condition_filtering_pct": 100,"rows_for_plan": 100145,"cost_for_plan": 20382,"sort_cost": 100145,"new_cost_for_plan": 120527,"chosen": true}] /* considered_execution_plans */},{"attaching_conditions_to_tables": {"original_condition": "(`employees`.`name` > 'a')","attached_conditions_computation": [] /* attached_conditions_computation */,"attached_conditions_summary": [{"table": "`employees`","attached": "(`employees`.`name` > 'a')"}] /* attached_conditions_summary */} /* attaching_conditions_to_tables */},{"clause_processing": {"clause": "ORDER BY","original_clause": "`employees`.`position`","items": [{"item": "`employees`.`position`"}] /* items */,"resulting_clause_is_simple": true,"resulting_clause": "`employees`.`position`"} /* clause_processing */},{"reconsidering_access_paths_for_index_ordering": {"clause": "ORDER BY","steps": [] /* steps */,"index_order_summary": {"table": "`employees`","index_provides_order": false,"order_direction": "undefined","index": "unknown","plan_changed": false} /* index_order_summary */} /* reconsidering_access_paths_for_index_ordering */},{"refine_plan": [{"table": "`employees`"}] /* refine_plan */}] /* steps */} /* join_optimization */},{"join_execution": {"select#": 1,"steps": [{"filesort_information": [{"direction": "asc","table": "`employees`","field": "position"}] /* filesort_information */,"filesort_priority_queue_optimization": {"usable": false,"cause": "not applicable (no LIMIT)"} /* filesort_priority_queue_optimization */,"filesort_execution": [] /* filesort_execution */,"filesort_summary": {"rows": 100003,"examined_rows": 100003,"number_of_tmp_files": 30,"sort_buffer_size": 262056,"sort_mode": "<sort_key, packed_additional_fields>"} /* filesort_summary */}] /* steps */} /* join_execution */}] /* steps */}
常见sql优化
order by:
| EXPLAIN SELECT * FROM employees WHERE name = ‘LiLei’ AND position = ‘dev’ ORDER BY age; 结果分析:order by 会走索引,name肯定走索引,order by走索引不会提现在字段长度上面。Using filesort就是没有用到索引,但是没有filesort。 ![]() |
|---|
| explain select * from employees where name = ‘LiLei’ order by position; 结果分析:len = 74,用到了那么索引,但是后面用到position进行了排序,跳过age,所以出现Using filesort ![]() |
|---|
| explain select * from employees where name = ‘LiLei’ order by age,position; 结果分析:没有用到Using filesort,索引值用到了name,没有跳过age ![]() |
|---|
| explain select * from employees where name = ‘LiLei’ order by position,age; 结果分析:和上面一样,但是order by的顺序变了,出现了Using filesort,因为创建索引的顺序数name、age、position,排序的时候age和position的顺序颠倒了。 ![]() |
|---|
| explain select * from employees where name = ‘LiLei’ and age = 20 order by position,age; 结果分析:Extra中并未出现Using filesort,因为age为常量,在排序中呗优化,所以索引未颠倒,不会出啊先Using filesort。 ![]() |
|---|
| explain select * from employees where name = ‘LiLei’ order by age asc,position desc; 结果分析:虽然排序的字段列与索引顺序一样,且order by默认升序,这里position desc变成了降序,导致与索引的排序方式不同,从而产生Using filesort。Mysql8以上版本有降序索引可以支持该种查询方式。 ![]() |
|---|
| explain select * from employees where name in(‘LiLei’,’zhuge’) order by age,position; 结果分析:对于排序来说,多个相等条件也是范围查询 ![]() |
|---|
| explain select * from employees where name > ‘a’ order by name; 结果分析:用到了Using filesort,范围查找可能查询全部数据更快 ![]() 优化方式:使用覆盖索引 explain select name,age,position from employees where name > ‘a’ order by name; ![]() |
|---|
优化总结:
- 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;


















