目录1.数据准备2.实例一3.Mysql如何选择合适的索引?4.常见 sql 深入优化4.1.Order by与Group by优化4.2.分页查询优化4.3.join关联查询优化4.3.1.数据准备4.3.2.mysq
#1.建立员工表,并创建name,age,position索引,id为自增主键
CREATE TABLE `employees` (
`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=100010 DEFAULT CHARSET=utf8 COMMENT='员工记录表'
# 2.前面插入三条数据,并建立employees_min_copy表插入这三条数据
INSERT INTO employees (name,age,`position`,hire_time) VALUES
('LiLei',22,'manager','2021-08-17 21:00:55')
,('HanMeimei',23,'dev','2021-08-17 21:00:55')
,('Lucy',23,'dev','2021-08-17 21:00:55')
;
#3.再通过执行计划向表中插入十万条数据
#3.1建立存储过程,往employees表中插入数据(MySQL8.0版本)
DELIMITER $$
USE `zhebase`$$
DROP PROCEDURE IF EXISTS `BATch_insert_employees`$$
CREATE PROCEDURE `batch_insert_employees`(IN `start_number` BIGINT,IN `counts` BIGINT)
BEGIN
DECLARE start_number BIGINT DEFAULT start_number;
DECLARE stop_number BIGINT DEFAULT start_number;
SET stop_number=start_number + counts;
WHILE start_number < stop_number DO
INSERT INTO employees(name,age,position,hire_time) VALUES(CONCAT('zhang',start_number),start_number,'dev',now());
SET start_number=start_number+1;
END WHILE ;
COMMIT;
END$$
DELIMITER ;
#3.2执行存储过程插入十万条数据
CALL batch_insert_employees(1,100000);
1.联合索引第一个字段用范围不会走索引
EXPLaiN SELECT * FROM employees WHERE name > 'LiLei' AND age = 22 AND position ='manager';
原因:MySQL 内部可能觉得第一个字段就用范围,结果集应该很大,还需要回表,回表效率不高,不如直接采用全表扫描 但是我们可以强制走索引
EXPLAIN SELECT * FROM employees force index(idx_name_age_position) WHERE name > 'LiLei' AND age = 22 AND position ='manager';
-- 关闭查询缓存
set global query_cache_size=0;
set global query_cache_type=0;
-- 执行时间0.321s
SELECT * FROM employees WHERE name > 'LiLei';
-- 执行时间0.458s
SELECT * FROM employees force index(idx_name_age_position) WHERE name > 'LiLei';
使用了强制走索引让联合索引第一个字段范围查找也走索引,扫描的行rows看上去也少了点,但是最终查找效率不一定比全表扫描高,因为回表效率不高
对于这种情况,如果可以使用覆盖索引,就使用覆盖索引进行优化
EXPLAIN SELECT name,age,position FROM employees WHERE name > 'LiLei' AND age = 22 AND position ='manager';
2.in 和 or 在表数据量比较大的情况会走索引,在表记录不多的情况下会选择全表扫描
EXPLAIN SELECT * FROM employees
WHERE name in ('LiLei','HanMeimei','Lucy')
AND age = 22
AND position ='manager';
#表数据量大走索引,数据量小全表扫描
EXPLAIN SELECT * FROM employees
WHERE (name = 'LiLei' or name = 'HanMeimei')
AND age = 22
AND position ='manager';
将十万行数据的employees表复制一份插入几行数据,再进行查询
发现进行了全表扫描
3.like xx% 无论数据量多少一般情况都会走索引
EXPLAIN SELECT * FROM employees WHERE name like 'LiLei%' AND age = 22 AND position ='manager';
MySQL 底层使用索引下推(Index Condition Pushdown,ICP) 来对 like xx%进行优化。
索引下推: 对于辅助的联合索引(idx_name_age_position),通常按照最左前缀原则,SELECT * FROM employees WHERE name like 'LiLei%' AND age = 22 AND position ='manager'
因为在 name 是范围查询,过滤完后,age 和 position 是无序的,后续索引无法使用,只会走name字段索引。
MySQL 范围查找为什么没有使用索引下推优化? 可能因为范围查找结果集一般较大,like xx%在大多数情况下,过滤后结果集较小。而结果集大的时候,每次检索出来都要匹配后面的字段,不一定比立即回表要快。但是也不是绝对的,有些时候 Like xx%也不会走索引下推。
先来看两条 SQL 语句:
# MySQL直接使用全表扫描
EXPLAIN select * from employees where name > 'a';
# MySQL走索引
EXPLAIN select * from employees where name > 'zzz';
我们发现第一条 SQL 进行了全表扫描,第二条 SQL 走了索引。对应第一条SQL,MySQL 通过计算执行成本发现走索引成本比全部扫描更高(走索引需要遍历 name 字段,再进行回表操作查出最终数据,比直接查聚簇索引树更慢)。对于这种情况可以使用覆盖索引进行优化
。至于 MySQL 如何选择最终索引,可以用 Trace 工具进行查看。但开启trace工具会影响 MySQL 性能,用完之后需立即关闭。
#开启trace
set session optimizer_trace="enabled=on",end_markers_in_JSON=on;
#关闭trace
set session optimizer_trace="enabled=off";
#使用trace
select * from employees where name > 'a' order by position;
select * from infORMation_schema.OPTIMIZER_TRACE;
下面是执行后的Trace中的内容:
{
"steps": [
{
#第一阶段:SQL准备阶段,格式化sql
"join_preparation": {
"select#": 1,
"steps": [
{
"expanded_query": " 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` limit 0,200"
}
]
}
},
{
#第二阶段:SQL优化阶段
"join_optimization": {
"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')"
}
]
}
},
{
"substitute_generated_columns": {
}
},
{
#表依赖详情
"table_dependencies": [
{
"table": "`employees`",
"row_may_be_null": false,
"map_bit": 0,
"depends_on_map_bits": [
]
}
]
},
{
"ref_optimizer_key_uses": [
]
},
{
#预估表的访问成本
"rows_estimation": [
{
"table": "`employees`",
"range_analysis": {
"table_scan": { --全表扫描情况
"rows": 93205, --扫描行数
"cost": 9394.9 --查询成本
} ,
#查询可能使用的索引
"potential_range_indexes": [
{
"index": "PRIMARY", --主键索引
"usable": false, -- 是否使用
"cause": "not_applicable"
},
{
#辅助索引
"index": "idx_name_age_position",
"usable": true,
"key_parts": [
"name",
"age",
"position",
"id"
]
}
] ,
"setup_range_conditions": [
] ,
"group_index_range": {
"chosen": false,
"cause": "not_group_by_or_distinct"
} ,
"skip_scan_range": {
"potential_skip_scan_indexes": [
{
"index": "idx_name_age_position",
"usable": false,
"cause": "query_references_nonkey_column"
}
]
} ,
#分析各个索引使用成本
"analyzing_range_alternatives": {
"range_scan_alternatives": [
{
"index": "idx_name_age_position",
"ranges": [
"a < name" --索引使用范围
] ,
"index_dives_for_eq_ranges": true,
"rowid_ordered": false, --使用该索引获取的记录是否按照主键排序
"using_mrr": false,
"index_only": false, --是否使用覆盖索引
"rows": 46602, --索引扫描行数
"cost": 16311, --索引使用成本
"chosen": false, --是否选择该索引
"cause": "cost"
}
] ,
"analyzing_roWorder_intersect": {
"usable": false,
"cause": "too_few_roworder_scans"
}
}
}
}
]
},
{
"considered_execution_plans": [
{
"plan_prefix": [
] ,
"table": "`employees`",
"best_Access_path": { --最优访问路径
"considered_access_paths": [ --最终选择的访问路径
{
"rows_to_scan": 93205,
"filtering_effect": [
] ,
"final_filtering_effect": 0.5,
"access_type": "scan", --访问类型:为scan,全表扫描
"resulting_rows": 46602,
"cost": 9392.8,
"chosen": true --确定选择
}
]
} ,
"condition_filtering_pct": 100,
"rows_for_plan": 46602,
"cost_for_plan": 9392.8,
"chosen": true
}
]
},
{
"attaching_conditions_to_tables": {
"original_condition": "(`employees`.`name` > 'a')",
"attached_conditions_computation": [
{
"table": "`employees`",
"rechecking_index_usage": {
"recheck_reason": "low_limit",
"limit": 200,
"row_estimate": 46602
}
}
] ,
"attached_conditions_summary": [
{
"table": "`employees`",
"attached": "(`employees`.`name` > 'a')"
}
]
}
},
{
"optimizing_distinct_group_by_order_by": {
"simplifying_order_by": {
"original_clause": "`employees`.`position`",
"items": [
{
"item": "`employees`.`position`"
}
] ,
"resulting_clause_is_simple": true,
"resulting_clause": "`employees`.`position`"
}
}
},
{
"reconsidering_access_paths_for_index_ordering": {
"clause": "ORDER BY",
"steps": [
] ,
"index_order_summary": {
"table": "`employees`",
"index_provides_order": false,
"order_direction": "undefined",
"index": "unknown",
"plan_changed": false
}
}
},
{
"finalizing_table_conditions": [
{
"table": "`employees`",
"original_table_condition": "(`employees`.`name` > 'a')",
"final_table_condition ": "(`employees`.`name` > 'a')"
}
]
},
{
"refine_plan": [
{
"table": "`employees`"
}
]
},
{
"considering_tmp_tables": [
{
"adding_sort_to_table_in_plan_at_position": 0
}
]
}
]
}
},
{
#第三阶段:SQL执行阶段
"join_execution": {
"select#": 1,
"steps": [
{
"sorting_table_in_plan_at_position": 0,
"filesort_information": [
{
"direction": "asc",
"table": "`employees`",
"field": "position"
}
] ,
"filesort_priority_queue_optimization": {
"limit": 200,
"chosen": true
} ,
"filesort_execution": [
] ,
"filesort_summary": {
"memory_available": 262144,
"key_size": 40,
"row_size": 186,
"max_rows_per_buffer": 201,
"num_rows_estimate": 285696,
"num_rows_found": 100003,
"num_initial_chunks_spilled_to_disk": 0,
"peak_memory_used": 38994,
"sort_alGorithm": "std::stable_sort",
"unpacked_addon_fields": "using_priority_queue",
"sort_mode": "<fixed_sort_key, additional_fields>"
}
}
]
}
}
]
}
由 Trace字段可知,全表扫描的 cost_for_plan = 9394.9 小于使用索引 cost_for_plan = 16311,故最终选择全表扫描。
# 案例1
explain select * from employees where name = 'Lucy' and position = 'dev' order by age;
分析: 案例1 由最左前缀法则分析出索引中间不能出现断层,只使用了 name 索引前缀,也可以从key_len = 3n + 2 看出。age 索引列用在排序过程中,因为Extra字段里没有 Using filesort 而是 Using index condition 。
#案例2
explain select * from employees where name = 'Lucy' order by position;
分析: 案例2 索引查询使用了 name 索引前缀,但排序由于跳过了 age 所以Extra字段出现了 Using filesort 。
#案例3
explain select * from employees where name = 'Lucy' order by age, position;
分析: 案例3 查询时使用了 name 索引,age 和 postion 用于排序,不会出现 Using filesort
#案例4
explain select * from employees where name = 'Lucy' order by position,age;
分析: 案例4 查询时使用了 name 索引,age 和 postion 顺序与创建索引树不一致,出现了 Using filesort
#案例5
explain
select * from employees
where name = 'Lucy'
and age = 22
order by position,age;
分析: 案例5 查询时使用了 name 索引,age 和 postion 顺序与创建索引树不一致,但 name、age 为常量,MySQL 会自动优化,不会出现 Using filesort
#案例6
explain select * from employees where name = 'Lucy' order byage,position desc;
分析: 案例6 排序顺序一样,但 order by 默认升序,导致与索引的排序方式不同,出现了 Using filesort 。 MySQL8.0 以上版本有降序索引可以支持这种查询。
#案例7
explain select * from employees where name = 'Lucy' or name = 'LiLei' order by age;
分析: 案例7 对于排序来说,多个相等条件也是范围查询,出现了 Using filesort 。
#案例8
#SQL-1
explain select * from employees where name > 'zzz' order by name;
#SQL-2
explain select * from employees where name > 'a' order by name;
分析: 案例8 原因同前面的例子,可以使用覆盖索引优化。
MySQL排序总结:
1、MySQL支持两种方式的排序 filesort 和 index,Using index是指MySQL扫描索引本身完成排序。Using filesort 是指MySQL扫描聚簇索引(整张表)进行排序。index效率高,filesort效率低。
2、order by 满足两种情况会使用 Using index(不绝对)
3、尽量在索引列上完成排序,遵循最左前缀法则。
4、如果 order by 的条件不在索引列上,就会产生Using filesort。
5、能用覆盖索引尽量用覆盖索引
6、group by 与 order by 很类似,其实质是先排序后分组(group by 底层:先执行一次 order by 再进行分组),遵照索引创建顺序的最左前缀法则。对于group by的优化如果不需要排序的可以加上order by null 禁止排序。注意,where高于having,能写在where中的限定条件就不要去having限定了。
Using filesort 文件排序原理 filesort文件排序方式有:
MySQL 通过比较系统变量 max_length_for_sort_data(默认1024字节) 的大小和需要查询的字段总大小来判断使用哪种排序模式。
select * from employees where name = 'Lucy' order by position;
"join_execution": { --Sql执行阶段
"select#": 1,
"steps": [
{
"filesort_information": [
{
"direction": "asc",
"table": "`employees`",
"field": "position"
}
] ,
"filesort_priority_queue_optimization": {
"usable": false,
"cause": "not applicable (no LIMIT)"
} ,
"filesort_execution": [
] ,
"filesort_summary": { --文件排序信息
"rows": 10000, --预计扫描行数
"examined_rows": 10000, --参与排序的行
"number_of_tmp_files": 3, --使用临时文件的个数,如果为0代表全部使用的sort_buffer内存排序,否则使用的磁盘文件排序
"sort_buffer_size": 262056, --排序缓存的大小,单位Byte
"sort_mode": "<sort_key, packed_additional_fields>" --排序方式,此处是路排序
}
}
]
}
单路排序会把所有需要查询的字段都放到 sort buffer 中排序,而双路排序只会把主键和需要排序的字段放到 sort buffer 中进行排序,然后再通过主键回到原表查询需要的字段。
单路排序过程:
双路排序过程:
select * from employees limit 10000,10
这条 SQL 语句实际查询了 10010 条记录,然后丢弃了前面的 10000 条记录,所以,在 数据量很大时,执行效率是非常非常低的。一般需要对分页查询进行优化。 优化方法: 1.根据自增且连续的主键排序的分页查询
select * from employees where id > 90000 limit 5;
当一个表的主键连续且自增时,可以使用该方法进行优化,但如果自增不连续会造成数据丢失。
2.根据非主键字段排序的分页查询
#优化前
select * from employees ORDER BY name limit 90000,5;
#优化后
select * from employees e
inner join (select id from employees order by name limit 90000,5) ed
on e.id = ed.id;
先通过排序和分页操作先查出主键,然后根据主键查出对应的记录。
#示例表
# 创建t1,t2表,主键id,单值索引a
CREATE TABLE `t1` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`a` int(11) DEFAULT NULL,
`b` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_a` (`a`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
create table t2 like t1;
#存储过程往t1,t2表插入数据
DELIMITER $$
USE `zhebase`$$
DROP PROCEDURE IF EXISTS `batch_insert_t1`$$
CREATE PROCEDURE `batch_insert_t1`(IN `start_number` BIGINT,IN `counts` BIGINT)
BEGIN
DECLARE start_number BIGINT DEFAULT start_number;
DECLARE stop_number BIGINT DEFAULT start_number;
SET stop_number=start_number + counts;
WHILE start_number < stop_number DO
INSERT INTO t1(a,b) VALUES(start_number,start_number);
SET start_number=start_number+1;
END WHILE ;
COMMIT;
END$$
DELIMITER ;
DELIMITER $$
USE `zhebase`$$
DROP PROCEDURE IF EXISTS `batch_insert_t2`$$
CREATE PROCEDURE `batch_insert_t2`(IN `start_number` BIGINT,IN `counts` BIGINT)
BEGIN
DECLARE start_number BIGINT DEFAULT start_number;
DECLARE stop_number BIGINT DEFAULT start_number;
SET stop_number=start_number + counts;
WHILE start_number < stop_number DO
INSERT INTO t2(a,b) VALUES(start_number,start_number);
SET start_number=start_number+1;
END WHILE ;
COMMIT;
END$$
DELIMITER ;
#执行存储过程往t1表插入10000条记录,t2表插入100条记录
CALL batch_insert_t1(1,10000);
CALL batch_insert_t2(1,100);
1.嵌套循环连接 Nested-Loop Join(NLJ) 算法 原理:一次一行循环地从第一张表(驱动表)中读取行,在这行数据中取到关联字段,根据关联字段在另一张表(被驱动表)里取出满足条件的行,然后取出两张表的结果合集。
explain select * from t1 inner join t2 on t1.a= t2.a;
从执行计划可以了解的信息:
整个过程会读取 t2 表的所有数据(扫描100行),然后遍历这每行数据中字段 a 的值,根据 t2 表中 a 的值索引扫描 t1 表中的对应行(扫描100次 t1 表的索引,1次扫描可以认为最终只扫描 t1 表一行完整数据,也就是总共 t1 表也扫描了100行)。因此整个过程扫描了 200 行 。
2. 基于块的嵌套循环连接 Block Nested-Loop Join(BNL)算法 原理:把驱动表的数据读入到 join_buffer 中,然后扫描被驱动表,把被驱动表每一行取出来跟 join_buffer 中的数据做对比
explain select * from t1 inner join t2 on t1.b= t2.b;
整个过程对表 t1 和 t2 都做了一次全表扫描,因此扫描的总行数为10000(表 t1 的数据总量) + 100(表 t2 的数据总量) = 10100。并且 join_buffer 里的数据是无序的,因此对表 t1 中的每一行,都要做 100 次判断,所以内存中的判断次数是 100 * 10000= 100 万次(非扫描次数) 。 注意: join_buffer 的大小是由参数 join_buffer_size 控制,默认256k。如果 t2 放不下就会使用分段策略(先从 t2 表取出部分数据,比对完就清空 join_buffer,再重新拿出来余下的部分进行比对)。
被驱动表的关联字段无索引为什么要选择使用 BNL 算法而不使用 NLJ 算法? 如第二条 SQL,如果使用 NLJ 算法扫描行数为 100 * 10000 = 100万,这个是磁盘扫描。使用 BNL 算法仅需扫描 100100 行。
对于表关联 SQL 的优化
select * from t2 straight_join t1 on t2.a = t1.a; 代表指定mysql选着 t2 表作为驱动表
原则:小表驱动大表
# in 先执行括号里面的
select * from A where id in (select id from B)
#exists 先执行括号外面的
#select * 可以用 select 1 替换,没有区别
#exists 子查询内部会进行优化,并非逐条对比
#exists 子查询往往也可以用 jion 来代替,何种最优需要具体问题具体分析
select * from A where exists (select 1 from B where B.id = A.id)
注意:根据某个字段 count 不会统计字段为 null 的行
#扫描二级索引,按行累加
explain select count(1) from employees;
#扫描辅助索引按行累加(辅助索引比聚簇索引小)
explain select count(id) from employees;
#把 name 拿到内存,不为 null 就累加
explain select count(name) from employees;
#不取值,按行累加
explain select count(*) from employees;
四条语句的效率几乎可以忽略,效率对比如下: 字段有索引: count(* )≈count(1)>count(字段)>count(主键 id) 段)>count(主键 id) 字段无索引: count(*)≈count(1)>count(主键 id)>count(字段)
常见优化方法:
show table status
,它是一个估值,使用该查询效率很高到此这篇关于MySQL索引优化实例分析的文章就介绍到这了,更多相关MySQL索引优化内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
--结束END--
本文标题: MySQL索引优化实例分析
本文链接: https://www.lsjlt.com/news/33503.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-09
2024-05-09
2024-05-09
2024-05-09
2024-05-08
2024-05-08
2024-05-08
2024-05-08
2024-05-08
2024-05-08
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0