Explain 分析工具可以模拟sql执行过程,我们可以借此可以发现其性能瓶颈,更精准的对sql或表结构调优。
1、explain字段内容释义
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c375d675efd6786a1c6eab74ca905f8d.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3e2b791c33511276d20689a501b13b26.png)
在Type列中查询的性能:
system>const>eq_ref>ref>range>index>all,尽量不要让表走全表扫描(all级别),尽量优化在range以上(若数据量很小,那没关系)。
2、explain示例
下面通过几个SQL查询的例子给大家列下上面explain工具分析出现的情况,示例表user结构为:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3cd4010620216c3898f5e6c7413447a4.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bdf18d7a709dc0adea54112dd0183e0c.png)
1) 通过此explain分析我们能看到的信息为:是简单的sql查询,对user表进行全表扫描(all)查询,没有使用索引,可能扫描的行数为5;
explain select * from user;
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5376ad6703e9cdf9ed56e3dad12c80de.png)
2)通过此explain分析我们能看到的信息为:是简单(simple)的sql查询,对表user使用主键索引进行查询,其查询类型为常量(const)表示返回是1条记录,索引的长度为4字节(因为id为int类型,int类型为4字节),扫描的行数为1行。
explain select * from user where id=2;
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/553cbc575adf44e3411e66097f35a4ee.png)
3)通过此explain分析我们能看到的信息为:是简单(simple)的sql查询,对表user使用主键索引进行查询,其查询类型为范围(range)表示返回多行,索引的长度为4字节(因为id为int类型,int类型为4字节),扫描的行数为3行,extra附加信息字段显示查询的字段信息未被索引覆盖(走的聚簇索引)。
explain select * from user where id>2;
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/01312603ab03dd1b0127c8afd5baaead.png)
4)通过此explain分析我们能看到的信息为:是简单(simple)的sql查询,对表user使用普通索引进行查询,其查询类型为ref表示可能返回多行,索引使用了三个字段,但只用到了name字段所以长度为28字节(因为name为var(25)类型,此表字符集utf8下:25 3+3),扫描的行数为1行,extra附加信息字段显示查询的字段信息不完全被索引覆盖,即select后面查询的信息不能完全在索引中找到。
explain select * from user where name=‘lisi’;
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/51c812cbe9a8a8fbb2f26570287f79f6.png)
5)表示此表对user表使用普通索引进行查询索引使用了三个字段,但只用到了name字段所以长度为28字节(因为name为var(25)类型,此表字符集utf8下:253+3),扫描的行数为1行,extra附加信息字段显示查询的字段信息不完全被索引覆盖,即select后面查询的信息不能完全在索引中找到,还有使用的filesort排序未使用索引排序;
explain select * from user where name=‘lisi’ order by id;
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/4e924a78960a0f1a1835f83ded83e78a.png)
6)针对上个sql,发现此sql走了索引排序,因为name就在二级索引中,并已经排好序了;
explain select * from user where name=‘lisi’ order by name;
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/67a84df00ca7456d3b0af145b1efb0c3.png)
7)此即是多个sql执行的分析情况,执行顺序为id=2的sql先执行,id=1的sql后执行且表依赖于id=2的查询
explain select * from (select * from user where id=1) a;
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2f149098c129bef9f5f5302ae3c1c1f6.png)