各位用户为了找寻关于Mysql实验之使用explain分析索引的走向的资料费劲了很多周折。这里教程网为您整理了关于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

建表语句

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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;

准备的查询语句

? 1 2 3 4 5 6 7 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 条件

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

结果

分析

 

是否走索引 索引名称 扫描记录数 是 user_name 1

使用 email 条件

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

结果

分析

 

是否走索引 索引名称 扫描记录数 是 complex_index 7

使用 email + mobile + sex条件

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

结果

分析

 

是否走索引 索引名称 扫描记录数 是 complex_index 1

使用 email + mobile 条件

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

结果

分析

 

是否走索引 索引名称 扫描记录数 是 complex_index 7

使用 email + sex 条件

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

结果

分析

 

][3] 是否走索引 索引名称 扫描记录数 是 complex_index 7

使用 sex + mobile 条件

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

结果

分析

 

是否走索引 索引名称 扫描记录数 否   97185

使用 mobile+ sex 条件

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

结果

分析

 

是否走索引 索引名称 扫描记录数 否   97185

结论

通过上面的结果可以得知,当设置了组合索引之后,合理的使用查询条件的顺序是可以避免sql语句的慢查询的

原文链接:https://segmentfault.com/a/1190000008919846