MySql 笔记(二)分析sql语句
- explain的使用
explain的使用
- 使用EXPLAIN关键字可以模拟优化器执行SQL语句,有助于我们来分析sql语句的执行过程。
- 首先,在这里先建立一个students表,id为主键、name、age均为索引。
- 如下所示,在普通sql语句前加上explain便能够执行sql语句的分析了:
- 那么,我们可以分析以下这些参数的作用:
- id 对于不同的table,id值越大,代表被查询的优先级越高,如嵌套查询,子查询优先
- select_type 从上到下效率依次降低
1.SIMPLE
简单的select查询,查询中不包含子查询或者union
2.PRIMARY
若查询中包含子查询,name最外层标记为PRIMARY
3.SUBQUERY
若该查询为where中的子查询,则标记为SUBQUERY
explain select * from students where name= (select name from students where id=201521);
4.DERIVED(衍生的)
若该查询为from中的子查询,则标记为DERIVED(Mysql5.7没有这个了)
explain select * from (select * from students where id=201521) as a;
5.UNION
6.UNION RESULT
explain select * from students where id>201521 union select * from students where age>22;
- table 当前使用的表
- type 显示的是访问类型,是较为重要的一个指标,执行效率依次降低,一般来说,我们优化的话,至少要range,最好到ref或以上,可取值为:
1.NULL 不访问任何表、索引,直接返回数据
explain select now();
2.system 表只有一行记录(等于系统表),这是const类型的特例,一般不会出现
3.const 表示通过索引一次就找到了,一般是根据主键或者唯一索引进行查询,只返回一条数据
explain select * from students where id=201521;
4.eq_ref 与const的区别就是使用的关联查询,它使用主键或者唯一索引进行关联查询,查出的记录只有一条,常见于主键或者唯一索引扫描
在这里建了一个和students结构一样的表classmates,两个表中谁的数据行少,谁就进行全表扫描。
explain SELECT * from students s,classmates c where s.id=c.id ;
5.ref 与const的区别就是非唯一性的索引扫描,返回匹配的所有行
explain select * from students where age=18;
6.range 范围查询,where之后出现between,<,>,in等操作
7.index index与all的区别在于,他只遍历了索引树,就获取到了select要的数据,比如通过主键查找主键,通过联合索引查找联合索引中的字段,all是遍历了整个数据文件,就是全表扫描,所以他比all要快
explain select id from students where id=201521;
8.all 遍历全表以找到匹配的行