欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

MySQL索引優(yōu)化實例分析

 更新時間:2022年07月29日 15:19:15   作者:Hz488  
這篇文章主要介紹了MySQL索引優(yōu)化實例分析,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下

1.數(shù)據(jù)準備

#1.建立員工表,并創(chuàng)建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.前面插入三條數(shù)據(jù),并建立employees_min_copy表插入這三條數(shù)據(jù)
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.再通過執(zhí)行計劃向表中插入十萬條數(shù)據(jù)
#3.1建立存儲過程,往employees表中插入數(shù)據(jù)(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執(zhí)行存儲過程插入十萬條數(shù)據(jù)
CALL batch_insert_employees(1,100000);

2.實例一

1.聯(lián)合索引第一個字段用范圍不會走索引  

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

 原因:MySQL 內(nèi)部可能覺得第一個字段就用范圍,結果集應該很大,還需要回表,回表效率不高,不如直接采用全表掃描 但是我們可以強制走索引

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;
-- 執(zhí)行時間0.321s
SELECT * FROM employees WHERE name > 'LiLei';
-- 執(zhí)行時間0.458s
SELECT * FROM employees force index(idx_name_age_position) WHERE name > 'LiLei';

 使用了強制走索引讓聯(lián)合索引第一個字段范圍查找也走索引,掃描的行rows看上去也少了點,但是最終查找效率不一定比全表掃描高,因為回表效率不高

對于這種情況,如果可以使用覆蓋索引,就使用覆蓋索引進行優(yōu)化 

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

2.in 和 or 在表數(shù)據(jù)量比較大的情況會走索引,在表記錄不多的情況下會選擇全表掃描

EXPLAIN SELECT * FROM employees
WHERE name in ('LiLei','HanMeimei','Lucy')
AND age = 22
AND position ='manager';
#表數(shù)據(jù)量大走索引,數(shù)據(jù)量小全表掃描
EXPLAIN SELECT * FROM employees
WHERE (name = 'LiLei' or name = 'HanMeimei')
AND age = 22 
AND position ='manager';

 將十萬行數(shù)據(jù)的employees表復制一份插入幾行數(shù)據(jù),再進行查詢 

發(fā)現(xiàn)進行了全表掃描 

3.like xx% 無論數(shù)據(jù)量多少一般情況都會走索引

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

 MySQL 底層使用索引下推(Index Condition Pushdown,ICP) 來對 like xx%進行優(yōu)化。

索引下推: 對于輔助的聯(lián)合索引(idx_name_age_position),通常按照最左前綴原則,SELECT * FROM employees WHERE name like 'LiLei%' AND age = 22 AND position ='manager' 因為在 name 是范圍查詢,過濾完后,age 和 position 是無序的,后續(xù)索引無法使用,只會走name字段索引。

  • MySQL5.6 以前: 先在索引樹中匹配 name 是 'LiLei' 開頭的索引,然后根據(jù)索引下的主鍵進行回表操作,在主鍵索引上在匹配 age 和 position
  • MySQL 5.6以后: 引入索引下推,先在索引樹種匹配 name 是 'LiLei' 開頭的索引,同時將該所與樹通有的所有條件字段進行判斷,過濾掉不符合條件的記錄再回表匹配其他條件及查詢整行數(shù)據(jù)。
  • 優(yōu)點: 過濾掉不符合條件的記錄之后再回表,可以有效的減少回表次數(shù),提高查詢效率。

MySQL 范圍查找為什么沒有使用索引下推優(yōu)化?  可能因為范圍查找結果集一般較大,like xx%在大多數(shù)情況下,過濾后結果集較小。而結果集大的時候,每次檢索出來都要匹配后面的字段,不一定比立即回表要快。但是也不是絕對的,有些時候 Like xx%也不會走索引下推。

3.MySQL如何選擇合適的索引?

先來看兩條 SQL 語句:

# MySQL直接使用全表掃描
EXPLAIN select * from employees where name > 'a';
# MySQL走索引
EXPLAIN select * from employees where name > 'zzz';

 我們發(fā)現(xiàn)第一條 SQL 進行了全表掃描,第二條 SQL 走了索引。對應第一條SQL,MySQL 通過計算執(zhí)行成本發(fā)現(xiàn)走索引成本比全部掃描更高(走索引需要遍歷 name 字段,再進行回表操作查出最終數(shù)據(jù),比直接查聚簇索引樹更慢)。對于這種情況可以使用覆蓋索引進行優(yōu)化。至于 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;

下面是執(zhí)行后的Trace中的內(nèi)容:

{
 ?"steps": [
 ? ?{
 ? ? ?#第一階段:SQL準備階段,格式化sql
 ? ? ?"join_preparation": {
 ? ? ? ?"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` limit 0,200"
 ? ? ? ? ?}
 ? ? ? ?] /* steps */
 ? ? ?} /* join_preparation */
 ? ?},
 ? ?{
 ? ? ?#第二階段:SQL優(yōu)化階段
 ? ? ?"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')"
 ? ? ? ? ? ? ? ?}
 ? ? ? ? ? ? ?] /* 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": 93205, --掃描行數(shù)
 ? ? ? ? ? ? ? ? ? ?"cost": 9394.9 --查詢成本
 ? ? ? ? ? ? ? ? ?} /* table_scan */,
 ? ? ? ? ? ? ? ? ?#查詢可能使用的索引
 ? ? ? ? ? ? ? ? ?"potential_range_indexes": [
 ? ? ? ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ? ? ? ?"index": "PRIMARY", ?--主鍵索引
 ? ? ? ? ? ? ? ? ? ? ?"usable": false, -- 是否使用
 ? ? ? ? ? ? ? ? ? ? ?"cause": "not_applicable"
 ? ? ? ? ? ? ? ? ? ?},
 ? ? ? ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ? ? ? ?#輔助索引
 ? ? ? ? ? ? ? ? ? ? ?"index": "idx_name_age_position",
 ? ? ? ? ? ? ? ? ? ? ?"usable": true,
 ? ? ? ? ? ? ? ? ? ? ?"key_parts": [
 ? ? ? ? ? ? ? ? ? ? ? ?"name",
 ? ? ? ? ? ? ? ? ? ? ? ?"age",
 ? ? ? ? ? ? ? ? ? ? ? ?"position",
 ? ? ? ? ? ? ? ? ? ? ? ?"id"
 ? ? ? ? ? ? ? ? ? ? ?] /* key_parts */
 ? ? ? ? ? ? ? ? ? ?}
 ? ? ? ? ? ? ? ? ?] /* potential_range_indexes */,
 ? ? ? ? ? ? ? ? ?"setup_range_conditions": [
 ? ? ? ? ? ? ? ? ?] /* setup_range_conditions */,
 ? ? ? ? ? ? ? ? ?"group_index_range": {
 ? ? ? ? ? ? ? ? ? ?"chosen": false,
 ? ? ? ? ? ? ? ? ? ?"cause": "not_group_by_or_distinct"
 ? ? ? ? ? ? ? ? ?} /* group_index_range */,
 ? ? ? ? ? ? ? ? ?"skip_scan_range": {
 ? ? ? ? ? ? ? ? ? ?"potential_skip_scan_indexes": [
 ? ? ? ? ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ? ? ? ? ?"index": "idx_name_age_position",
 ? ? ? ? ? ? ? ? ? ? ? ?"usable": false,
 ? ? ? ? ? ? ? ? ? ? ? ?"cause": "query_references_nonkey_column"
 ? ? ? ? ? ? ? ? ? ? ?}
 ? ? ? ? ? ? ? ? ? ?] /* potential_skip_scan_indexes */
 ? ? ? ? ? ? ? ? ?} /* skip_scan_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": 46602, --索引掃描行數(shù)
 ? ? ? ? ? ? ? ? ? ? ? ?"cost": 16311, --索引使用成本
 ? ? ? ? ? ? ? ? ? ? ? ?"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": { --最優(yōu)訪問路徑
 ? ? ? ? ? ? ? ? ?"considered_access_paths": [ --最終選擇的訪問路徑
 ? ? ? ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ? ? ? ?"rows_to_scan": 93205,
 ? ? ? ? ? ? ? ? ? ? ?"filtering_effect": [
 ? ? ? ? ? ? ? ? ? ? ?] /* filtering_effect */,
 ? ? ? ? ? ? ? ? ? ? ?"final_filtering_effect": 0.5,
 ? ? ? ? ? ? ? ? ? ? ?"access_type": "scan", --訪問類型:為scan,全表掃描
 ? ? ? ? ? ? ? ? ? ? ?"resulting_rows": 46602,
 ? ? ? ? ? ? ? ? ? ? ?"cost": 9392.8,
 ? ? ? ? ? ? ? ? ? ? ?"chosen": true ?--確定選擇
 ? ? ? ? ? ? ? ? ? ?}
 ? ? ? ? ? ? ? ? ?] /* considered_access_paths */
 ? ? ? ? ? ? ? ?} /* best_access_path */,
 ? ? ? ? ? ? ? ?"condition_filtering_pct": 100,
 ? ? ? ? ? ? ? ?"rows_for_plan": 46602,
 ? ? ? ? ? ? ? ?"cost_for_plan": 9392.8,
 ? ? ? ? ? ? ? ?"chosen": true
 ? ? ? ? ? ? ?}
 ? ? ? ? ? ?] /* considered_execution_plans */
 ? ? ? ? ?},
 ? ? ? ? ?{
 ? ? ? ? ? ?"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
 ? ? ? ? ? ? ? ? ?} /* rechecking_index_usage */
 ? ? ? ? ? ? ? ?}
 ? ? ? ? ? ? ?] /* attached_conditions_computation */,
 ? ? ? ? ? ? ?"attached_conditions_summary": [
 ? ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ? ?"table": "`employees`",
 ? ? ? ? ? ? ? ? ?"attached": "(`employees`.`name` > 'a')"
 ? ? ? ? ? ? ? ?}
 ? ? ? ? ? ? ?] /* attached_conditions_summary */
 ? ? ? ? ? ?} /* attaching_conditions_to_tables */
 ? ? ? ? ?},
 ? ? ? ? ?{
 ? ? ? ? ? ?"optimizing_distinct_group_by_order_by": {
 ? ? ? ? ? ? ?"simplifying_order_by": {
 ? ? ? ? ? ? ? ?"original_clause": "`employees`.`position`",
 ? ? ? ? ? ? ? ?"items": [
 ? ? ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ? ? ?"item": "`employees`.`position`"
 ? ? ? ? ? ? ? ? ?}
 ? ? ? ? ? ? ? ?] /* items */,
 ? ? ? ? ? ? ? ?"resulting_clause_is_simple": true,
 ? ? ? ? ? ? ? ?"resulting_clause": "`employees`.`position`"
 ? ? ? ? ? ? ?} /* simplifying_order_by */
 ? ? ? ? ? ?} /* optimizing_distinct_group_by_order_by */
 ? ? ? ? ?},
 ? ? ? ? ?{
 ? ? ? ? ? ?"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 */
 ? ? ? ? ?},
 ? ? ? ? ?{
 ? ? ? ? ? ?"finalizing_table_conditions": [
 ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ?"table": "`employees`",
 ? ? ? ? ? ? ? ?"original_table_condition": "(`employees`.`name` > 'a')",
 ? ? ? ? ? ? ? ?"final_table_condition ? ": "(`employees`.`name` > 'a')"
 ? ? ? ? ? ? ?}
 ? ? ? ? ? ?] /* finalizing_table_conditions */
 ? ? ? ? ?},
 ? ? ? ? ?{
 ? ? ? ? ? ?"refine_plan": [
 ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ?"table": "`employees`"
 ? ? ? ? ? ? ?}
 ? ? ? ? ? ?] /* refine_plan */
 ? ? ? ? ?},
 ? ? ? ? ?{
 ? ? ? ? ? ?"considering_tmp_tables": [
 ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ?"adding_sort_to_table_in_plan_at_position": 0
 ? ? ? ? ? ? ?} /* filesort */
 ? ? ? ? ? ?] /* considering_tmp_tables */
 ? ? ? ? ?}
 ? ? ? ?] /* steps */
 ? ? ?} /* join_optimization */
 ? ?},
 ? ?{
 ? ? ?#第三階段:SQL執(zhí)行階段
 ? ? ?"join_execution": {
 ? ? ? ?"select#": 1,
 ? ? ? ?"steps": [
 ? ? ? ? ?{
 ? ? ? ? ? ?"sorting_table_in_plan_at_position": 0,
 ? ? ? ? ? ?"filesort_information": [
 ? ? ? ? ? ? ?{
 ? ? ? ? ? ? ? ?"direction": "asc",
 ? ? ? ? ? ? ? ?"table": "`employees`",
 ? ? ? ? ? ? ? ?"field": "position"
 ? ? ? ? ? ? ?}
 ? ? ? ? ? ?] /* filesort_information */,
 ? ? ? ? ? ?"filesort_priority_queue_optimization": {
 ? ? ? ? ? ? ?"limit": 200,
 ? ? ? ? ? ? ?"chosen": true
 ? ? ? ? ? ?} /* filesort_priority_queue_optimization */,
 ? ? ? ? ? ?"filesort_execution": [
 ? ? ? ? ? ?] /* 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>"
 ? ? ? ? ? ?} /* filesort_summary */
 ? ? ? ? ?}
 ? ? ? ?] /* steps */
 ? ? ?} /* join_execution */
 ? ?}
 ?] /* steps */
}

由 Trace字段可知,全表掃描的 cost_for_plan = 9394.9 小于使用索引 cost_for_plan = 16311,故最終選擇全表掃描。

4.常見 SQL 深入優(yōu)化

4.1.Order by與Group by優(yōu)化

# 案例1
explain select * from employees where name = 'Lucy' and position = 'dev' order by age;

分析:  案例1 由最左前綴法則分析出索引中間不能出現(xiàn)斷層,只使用了 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字段出現(xiàn)了 Using filesort 。

#案例3
explain select * from employees where name = 'Lucy' ?order by age, position;

分析:  案例3 查詢時使用了 name 索引,age 和 postion 用于排序,不會出現(xiàn) Using filesort

#案例4
explain select * from employees where name = 'Lucy' ?order by position,age;

分析:  案例4 查詢時使用了 name 索引,age 和 postion 順序與創(chuàng)建索引樹不一致,出現(xiàn)了 Using filesort

#案例5
explain
select * from employees
where name = 'Lucy'
and age = 22
order by position,age;

分析:  案例5 查詢時使用了 name 索引,age 和 postion 順序與創(chuàng)建索引樹不一致,但 name、age 為常量,MySQL 會自動優(yōu)化,不會出現(xiàn) Using filesort

#案例6
explain select * from employees where name = 'Lucy' order byage,position desc;

分析:  案例6 排序順序一樣,但 order by 默認升序,導致與索引的排序方式不同,出現(xiàn)了 Using filesort 。 MySQL8.0 以上版本有降序索引可以支持這種查詢。

#案例7
explain select * from employees where name = 'Lucy' or name = 'LiLei' order by age;

 分析:  案例7 對于排序來說,多個相等條件也是范圍查詢,出現(xiàn)了 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 原因同前面的例子,可以使用覆蓋索引優(yōu)化。

MySQL排序總結:

1、MySQL支持兩種方式的排序 filesort 和 index,Using index是指MySQL掃描索引本身完成排序。Using filesort 是指MySQL掃描聚簇索引(整張表)進行排序。index效率高,filesort效率低。

2、order by 滿足兩種情況會使用 Using index(不絕對)

  • a.order by 語句使用索引最左前列。
  • b.使用 where 子句與 order by 子句條件列組合滿足索引最左前列。

3、盡量在索引列上完成排序,遵循最左前綴法則。

4、如果 order by 的條件不在索引列上,就會產(chǎn)生Using filesort。

5、能用覆蓋索引盡量用覆蓋索引

6、group by 與 order by 很類似,其實質(zhì)是先排序后分組(group by 底層:先執(zhí)行一次 order by 再進行分組),遵照索引創(chuàng)建順序的最左前綴法則。對于group by的優(yōu)化如果不需要排序的可以加上order by null 禁止排序。注意,where高于having,能寫在where中的限定條件就不要去having限定了。

Using filesort 文件排序原理 filesort文件排序方式有:

  • 單路排序是一次性取出滿足條件行的所有字段,然后在 sort buffer 中進行排序。用trace工具得到sort_mode信息顯示< sort_key, additional_fields >或者< sort_key, packed_additional_fields >
  • 雙路排序(又叫回表排序模式) :先根據(jù)相應的條件取出相應的排序字段和可以直接定位行數(shù)據(jù)的行 ID,然后在 sort buffer 中進行排序,排序完后需要再次取回其它需要的字段。用trace工具得到sort_mode信息顯示< sort_key, rowid >

MySQL 通過比較系統(tǒng)變量 max_length_for_sort_data(默認1024字節(jié)) 的大小和需要查詢的字段總大小來判斷使用哪種排序模式。

  • 字段的總長度 < max_length_for_sort_data ,使用單路排序
  • 字段的總長度 >max_length_for_sort_data ,使用雙路排序
 select * from employees where name = 'Lucy' order by position;
"join_execution": { ? ?--Sql執(zhí)行階段
 ? ? ? ?"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": 10000, ? ? ? ? ? ? ? ? ? ? ? ? ? --預計掃描行數(shù)
 ? ? ? ? ? ? ?"examined_rows": 10000, ? ? ? ? ? ? ? ? ?--參與排序的行
 ? ? ? ? ? ? ?"number_of_tmp_files": 3, ? ? ? ? ? ? ? ?--使用臨時文件的個數(shù),如果為0代表全部使用的sort_buffer內(nèi)存排序,否則使用的磁盤文件排序
 ? ? ? ? ? ? ?"sort_buffer_size": 262056, ? ? ? ? ? ? ?--排序緩存的大小,單位Byte
 ? ? ? ? ? ? ?"sort_mode": "<sort_key, packed_additional_fields>" ? ? ? --排序方式,此處是路排序
 ? ? ? ? ? ?} /* filesort_summary */
 ? ? ? ? ?}
 ? ? ? ?] /* steps */
 ? ? ?} /* join_execution */

單路排序會把所有需要查詢的字段都放到 sort buffer 中排序,而雙路排序只會把主鍵和需要排序的字段放到 sort buffer 中進行排序,然后再通過主鍵回到原表查詢需要的字段。

單路排序過程:

  • a.從索引 name 找到第一個滿足 name = 'Lucy' 條件的主鍵 id
  • b.回表根據(jù)主鍵 id 取出整行,取出所有字段的值,存入 sort_buffer 中
  • c.從索引name找到下一個滿足 name = 'Lucy' 條件的主鍵 id
  • d.重復步驟 2、3 直到不滿足 name = 'Lucy'
  • e.對 sort_buffer 中的數(shù)據(jù)按照字段 position 進行排序
  • f.返回結果

雙路排序過程:

  • a.從索引 name 找到第一個滿足 name ='Lucy' 的主鍵 id
  • b.根據(jù)主鍵 id 取出整行,把排序字段 position 和主鍵 id 這兩個字段放到 sort buffer 中
  • c.從索引 name 取下一個滿足 name = 'Lucy' 記錄的主鍵 id
  • d.重復 3、4 直到不滿足 name = 'Lucy'
  • e.對 sort_buffer 中的字段 position 和主鍵 id 按照字段 position 進行排序
  • f.遍歷排序好的 id 和字段 position,按照 id 的值回到原表中取出所有字段的值返回

4.2.分頁查詢優(yōu)化

 select * from employees limit 10000,10

這條 SQL 語句實際查詢了 10010 條記錄,然后丟棄了前面的 10000 條記錄,所以,在 數(shù)據(jù)量很大時,執(zhí)行效率是非常非常低的。一般需要對分頁查詢進行優(yōu)化。 優(yōu)化方法: 1.根據(jù)自增且連續(xù)的主鍵排序的分頁查詢

 select * from employees where id > 90000 limit 5;

當一個表的主鍵連續(xù)且自增時,可以使用該方法進行優(yōu)化,但如果自增不連續(xù)會造成數(shù)據(jù)丟失

2.根據(jù)非主鍵字段排序的分頁查詢

#優(yōu)化前
select * from employees ORDER BY name limit 90000,5;
#優(yōu)化后
select * from employees e 
inner join (select id from employees order by name limit 90000,5) ed 
on e.id = ed.id;

先通過排序和分頁操作先查出主鍵,然后根據(jù)主鍵查出對應的記錄。 

4.3.join關聯(lián)查詢優(yōu)化

4.3.1.數(shù)據(jù)準備

#示例表
# 創(chuàng)建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表插入數(shù)據(jù)
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 ;
#執(zhí)行存儲過程往t1表插入10000條記錄,t2表插入100條記錄
CALL batch_insert_t1(1,10000);
CALL batch_insert_t2(1,100);

4.3.2.MySQL 表關聯(lián)常見的兩種算法

  • 嵌套循環(huán)連接 Nested-Loop Join(NLJ) 算法
  • 基于塊的嵌套循環(huán)連接 Block Nested-Loop Join(BNL)算法
  • MySQL對于被驅(qū)動表的關聯(lián)字段沒索引的關聯(lián)查詢,一般都會使用 BNL 算法。如果有索引一般選擇 NLJ 算法,有索引的情況下 NLJ 算法比 BNL算法性能更高

1.嵌套循環(huán)連接 Nested-Loop Join(NLJ) 算法 原理:一次一行循環(huán)地從第一張表(驅(qū)動表)中讀取行,在這行數(shù)據(jù)中取到關聯(lián)字段,根據(jù)關聯(lián)字段在另一張表(被驅(qū)動表)里取出滿足條件的行,然后取出兩張表的結果合集。

explain select * from t1 inner join t2 on t1.a= t2.a;

 從執(zhí)行計劃可以了解的信息:

  • a.驅(qū)動表是 t2,被驅(qū)動表是 t1( inner join 時 SQL優(yōu)化器會小表驅(qū)動大表,外連接則根據(jù)連接類型區(qū)分)
  • b.使用了 NLJ 算法。如果執(zhí)行計劃 Extra 中未出現(xiàn) Using join buffer 則表示使用的 join 算法是 NLJ

整個過程會讀取 t2 表的所有數(shù)據(jù)(掃描100行),然后遍歷這每行數(shù)據(jù)中字段 a 的值,根據(jù) t2 表中 a 的值索引掃描 t1 表中的對應行(掃描100次 t1 表的索引,1次掃描可以認為最終只掃描 t1 表一行完整數(shù)據(jù),也就是總共 t1 表也掃描了100行)。因此整個過程掃描了 200 行 。

2. 基于塊的嵌套循環(huán)連接 Block Nested-Loop Join(BNL)算法 原理:把驅(qū)動表的數(shù)據(jù)讀入到 join_buffer 中,然后掃描被驅(qū)動表,把被驅(qū)動表每一行取出來跟 join_buffer 中的數(shù)據(jù)做對比

explain select * from t1 inner join t2 on t1.b= t2.b;

 整個過程對表 t1 和 t2 都做了一次全表掃描,因此掃描的總行數(shù)為10000(表 t1 的數(shù)據(jù)總量) + 100(表 t2 的數(shù)據(jù)總量) = 10100。并且 join_buffer 里的數(shù)據(jù)是無序的,因此對表 t1 中的每一行,都要做 100 次判斷,所以內(nèi)存中的判斷次數(shù)是 100 * 10000= 100 萬次(非掃描次數(shù)) 。 注意: join_buffer 的大小是由參數(shù) join_buffer_size 控制,默認256k。如果 t2 放不下就會使用分段策略(先從 t2 表取出部分數(shù)據(jù),比對完就清空 join_buffer,再重新拿出來余下的部分進行比對)。

被驅(qū)動表的關聯(lián)字段無索引為什么要選擇使用 BNL 算法而不使用 NLJ 算法?          如第二條 SQL,如果使用 NLJ 算法掃描行數(shù)為 100 * 10000 = 100萬,這個是磁盤掃描。使用 BNL 算法僅需掃描 100100 行。

對于表關聯(lián) SQL 的優(yōu)化

  • 盡量少關聯(lián)(在阿里規(guī)范中,關聯(lián)表不能超過三種,可以后端代碼單獨查詢,循環(huán)關聯(lián))
  • 小表驅(qū)動大表,寫多表連接 SQL 時如果明確知道哪張表是小表可以用straight_join寫法固定連接驅(qū)動方式,節(jié)約 MySQL 優(yōu)化器判斷時間.select * from t2 straight_join t1 on t2.a = t1.a; 代表指定mysql選著 t2 表作為驅(qū)動表
  • 關聯(lián)字段加索引,大表關聯(lián)字段一定要加索引,盡量使得 MySQL 在進行 join 操作時選擇NLJ算法
  • 多表連接是非常難以優(yōu)化的,最好95%的場景都使用單表來完成,復雜場景交個JAVA代碼,大規(guī)模計算交給大數(shù)據(jù)工具,無需效率才考慮連接

4.4.in和exsits優(yōu)化

原則:小表驅(qū)動大表

# in 先執(zhí)行括號里面的
select * from A where id in (select id from B) ?
#exists 先執(zhí)行括號外面的
#select * 可以用 select 1 替換,沒有區(qū)別
#exists 子查詢內(nèi)部會進行優(yōu)化,并非逐條對比
#exists 子查詢往往也可以用 jion 來代替,何種最優(yōu)需要具體問題具體分析
select * from A where exists (select 1 from B where B.id = A.id)

4.5.count(*)查詢優(yōu)化

注意:根據(jù)某個字段 count 不會統(tǒng)計字段為 null 的行

#掃描二級索引,按行累加
explain select count(1) from employees;
#掃描輔助索引按行累加(輔助索引比聚簇索引?。?
explain select count(id) from employees;
#把 name 拿到內(nèi)存,不為 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(字段)

常見優(yōu)化方法:

  • 1.對于 MyISAM 存儲引擎的表做不帶 where 條件的 count 查詢性能是很高的,數(shù)據(jù)總行數(shù)直接寫在磁盤上,查詢不需要計算。innodb 存儲引擎的表則不會記錄(因為有MVCC機制)
  • 2.對與不用知道確切行的可以直接使用show table status,它是一個估值,使用該查詢效率很高
  • 3.將總數(shù)維護到 Redis 里面,插入或刪除表數(shù)據(jù)行的時候同時維護 Redis 里的表總行數(shù) key 的計數(shù)值(用 incr 或 decr 命令),但是這種方式可能不準,很難保證表操作和Redis 操作的事務一致性。
  • 4.增加數(shù)據(jù)庫計數(shù)表,插入或刪除表數(shù)據(jù)行的時候同時維護計數(shù)表,且它們在同一個事務里操作

5.索引設計原則

  • 1、代碼先行,索引后上,先開發(fā)完主體業(yè)務代碼,再把涉及到該表相關sql都要拿出來分析之后再建立索引。
  • 2、聯(lián)合索引盡量覆蓋條件,可以設計一個或者兩三個聯(lián)合索引(單值索引要少建),讓每一個聯(lián)合索引都盡量去包含SQL語句里的 where、order by、group by 的字段,且這些聯(lián)合索引字段順序盡量滿足 SQL查詢的最左前綴原則。
  • 3、不要在小基數(shù)字段上建立索引,無法進行快速的二分查找,不能能發(fā)揮出B+樹快速二分查找的優(yōu)勢來,沒有意義
  • 4、盡量對字段類型較小的列設計索引,盡量對字段類型較小的列設計索引,比如 Tinyint 之類,字段類型較小的話,占用磁盤空間小,搜索的時性能更好。
  • 5、長字符串可以采用前綴索引,比如針對某個字段的前20個字符建立索引,即:每個值的前20個字符放入索引樹中,搜索時會先匹配前而是個字符,再回表到聚簇索引取出來完整的 name 字段值進行比較。但排序(order by 和 group by)時無法使用該索引。
  • 6、where 與 order by 沖突時優(yōu)先 where,大多數(shù)情況下根據(jù)索引進行 where 篩選一般篩選出來的數(shù)據(jù)比較少,然后做排序成本會更低。
  • 7、基于慢SQL查詢做優(yōu)化,可以根據(jù)監(jiān)控后臺的一些慢SQL,針對這些慢 SQL 查詢做特定的索引優(yōu)化(MySQL有提供,只需設置具體參數(shù))。

到此這篇關于MySQL索引優(yōu)化實例分析的文章就介紹到這了,更多相關MySQL索引優(yōu)化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論