相關學習推薦:mysql教程
前言mysql索引底層數據結構與算法mysql性能優化原理-前篇實踐(1)–mysql性能優化
上一篇 《實踐(1)–mysql性能優化》我們講了數據庫表設計的一些原則,explain工具的介紹、sql語句優化索引的最佳實踐,本篇繼續來聊聊 mysql 如何選擇合適的索引。
mysql trace 工具
mysql 最終是否選擇走索引或者一張表涉及多個索引,最終是如何選擇索引,可以使用 trace 工具來一查究竟,開啟 trace工具會影響 mysql 性能,所以只能臨時分析 sql 使用,用完之后立即關閉。
案例分析
講 trace 工具之前我們先來看一個案例:
# 示例表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=4 default charset=utf8 comment='員工記錄表'; insert into employees(name,age,position,hire_time)values('zhangsan',23,'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());復制代碼mysql 如何選擇合適的索引
explain select * from employees where name > 'a';復制代碼如果用name索引需要遍歷name字段聯合索引樹,然后還需要根據遍歷出來的主鍵值去主鍵索引樹里再去查出最終數據,成本比全表掃描還高,可以用覆蓋索引優化,這樣只需要遍歷name字段的聯合索引樹就能拿到所有結果,如下:
explain select name,age,position from employees where name > 'a' ;復制代碼explain select * from employees where name > 'zzz' ;復制代碼對于上面這兩種 name>'a' 和 name>'zzz' 的執行結果,mysql最終是否選擇走索引或者一張表涉及多個索引,mysql最終如何選擇索引,我們可以用trace工具來一查究竟,開啟trace工具會影響mysql性能,所以只能臨時分析sql使用,用完之后立即關閉。
trace工具用法開啟/關閉trace
#開啟traceset session optimizer_trace="enabled=on",end_markers_in_json=on;#關閉traceset session optimizer_trace="enabled=off";復制代碼案例1
執行這兩句sql
select * from employees where name >'a' order by position;select * from information_schema.optimizer_trace; 復制代碼提出來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,
這個經營范圍要寫承若書嗎騰訊企業產品感恩上海行優質案例前瞻辦公移動化買了云服務器怎麼用幫忙看下這個能訪問加上訪問不了如何創建云服務器ecs域名預定競價規則是什么?如何選擇阿里云服務器配置怎樣正確合理的選購BlueHost虛擬主機?