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

概述

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

實驗目的

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

說明

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

準備工做

一、用戶表一張,有uid ,user_name,real_name ,eamil等字段,詳細見建表語句
二、在user_name字段下增長一個簡單索引user_name,在email,mobile,age三個字段下增長索引complex_index
三、表引擎使用MyISAM,增長
四、準備97000條數據(具體的能夠根據實際狀況來定數據量,這裏準備的是97000+)
五、實驗工具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語句的慢查詢的ui

相關文章
相關標籤/搜索