1. 程式人生 > 資料庫 >Mysql實驗之使用explain分析索引的走向

Mysql實驗之使用explain分析索引的走向

概述

索引是mysql的必須要掌握的技能,同時也是提供mysql查詢效率的手段。通過以下的一個實驗可以理解?mysql的索引規則,同時也可以不斷的來優化sql語句

實驗目的

本實驗是為了驗證組合索引的 最左原則

說明

此實驗只是為了驗證實際使用索引的結果,請忽略設計的合理性

準備工作

1、使用者表一張,有uid,user_name,real_name,eamil等欄位,詳細見建表語句
2、在user_name欄位下增加一個簡單索引user_name,在email,mobile,age三個欄位下增加索引complex_index
3、表引擎使用MyISAM,增加
4、準備97000條資料(具體的可以根據實際情況來定資料量,這裡準備的是97000+)

5、實驗工具Navcat

建表語句

DROP TABLE IF EXISTS `qz_users`;
CREATE TABLE `qz_users` (
 `uid` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '使用者的 UID',`user_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '使用者名稱',`real_name` varchar(128) CHARACTER SET utf8 DEFAULT NULL COMMENT '使用者姓名',`email` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT 'EMAIL',`mobile` varchar(16) CHARACTER SET utf8 DEFAULT NULL COMMENT '使用者手機',`password` varchar(32) CHARACTER SET utf8 DEFAULT NULL COMMENT '使用者密碼',`salt` varchar(16) CHARACTER SET utf8 DEFAULT NULL COMMENT '使用者附加混淆碼',`avatar_file` varchar(128) CHARACTER SET utf8 DEFAULT NULL COMMENT '頭像檔案',`sex` tinyint(1) DEFAULT NULL COMMENT '性別',`birthday` int(10) DEFAULT NULL COMMENT '生日',PRIMARY KEY (`uid`),KEY `user_name` (`user_name`(250)),KEY `complex_index` (`email`,`mobile`,`sex`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

準備的查詢語句

explain select * from qz_users where user_name = "ryanhe";
explain select * from qz_users where email = "x";
explain select * from qz_users where email = "x" and mobile = "x" and sex=1;
explain select * from qz_users where email = "x" and mobile = "x";
explain select * from qz_users where email = "x" and sex = "x";
explain select * from qz_users where sex = "x" and mobile = "x";
explain select * from qz_users where mobile = "x" and sex = "0";

結果分析

使用 user_name 條件

explain select * from qz_users where user_name= "x";

結果

分析

是否走索引 索引名稱 掃描記錄數
user_name 1

使用 email 條件

explain select * from qz_users where email = "x";

結果

分析

是否走索引 索引名稱 掃描記錄數
complex_index 7

使用 email + mobile + sex條件

explain select * from qz_users where email = "x" and mobile = "x" and sex=1;

結果

分析

是否走索引 索引名稱 掃描記錄數
complex_index 1

使用 email + mobile 條件

explain select * from qz_users where email = "x" and mobile = "x";

結果

分析

是否走索引 索引名稱 掃描記錄數
complex_index 7

使用 email + sex 條件

explain select * from qz_users where email = "x" and sex = "x";

結果

分析

][3] 是否走索引 索引名稱 掃描記錄數
complex_index 7

使用 sex + mobile 條件

explain select * from qz_users where sex = "x" and mobile = "x";

結果

分析

是否走索引 索引名稱 掃描記錄數
97185

使用 mobile+ sex 條件

explain select * from qz_users where mobile = "18602199680" and sex = "0";

結果

分析

是否走索引 索引名稱 掃描記錄數
97185

結論

通過上面的結果可以得知,當設定了組合索引之後,合理的使用查詢條件的順序是可以避免sql語句的慢查詢的