排序分组优化
where 条件和 on的判断这些过滤条件,作为优先优化的部门,是要被先考虑的!其次,如果有分组和排序,那么也要考虑grouo by 和order by。
1. 无过滤不索引
create index idx_age_deptid_name on emp (age,deptid,name);explain select * from emp where age=40 order by deptid;explain select * from emp order by age,deptid;explain select * from emp order by age,deptid limit 10;
![d4c28727ef6517a5fa4c5833ddacd5d9.png](https://img-blog.csdnimg.cn/img_convert/d4c28727ef6517a5fa4c5833ddacd5d9.png)
![fda4dc35b5faffa7c92d692c5e1e6cd3.png](https://img-blog.csdnimg.cn/img_convert/fda4dc35b5faffa7c92d692c5e1e6cd3.png)
using filesort说明进行了手工排序!原因在于没有where作为过滤条件!
![47536bd58593be2f2817c220761686d9.png](https://img-blog.csdnimg.cn/img_convert/47536bd58593be2f2817c220761686d9.png)
结论: 无过滤,不索引。where,limt都相当于一种过滤条件,所以才能使用上索引!
2. 顺序错,必排序
①explain select * from emp where age=45 order by deptid,name;
![4e71868b50e755b37c288cadf4e80721.png](https://img-blog.csdnimg.cn/img_convert/4e71868b50e755b37c288cadf4e80721.png)
②explain select * from emp where age=45 order by deptid,empno;
![b80aad69e60a3d9b124fdc86ddfd5300.png](https://img-blog.csdnimg.cn/img_convert/b80aad69e60a3d9b124fdc86ddfd5300.png)
empno字段并没有建立索引,因此也无法用到索引,此字段需要排序!
③explain select * from emp where age=45 order by name,deptid;
![6b19a151b7d1b1069f453d9fdccff7f5.png](https://img-blog.csdnimg.cn/img_convert/6b19a151b7d1b1069f453d9fdccff7f5.png)
where 两侧列的顺序可以变换,效果相同,但是order by列的顺序不能随便变换!
④explain select * from emp where deptid=45 order by age;
![9d051fa5f170bddac92fc2d0f4837308.png](https://img-blog.csdnimg.cn/img_convert/9d051fa5f170bddac92fc2d0f4837308.png)
deptid作为过滤条件的字段,无法使用索引,因此排序没法用上索引
3. 方向反,必排序
①explain select * from emp where age=45 order by deptid desc, name desc ;
![bf696e8257a848d290cf6840fb7ce0d5.png](https://img-blog.csdnimg.cn/img_convert/bf696e8257a848d290cf6840fb7ce0d5.png)
如果可以用上索引的字段都使用正序或者逆序,实际上是没有任何影响的,无非将结果集调换顺序。
![ad7910fc0388e31a3fc0f44cfee498ec.png](https://img-blog.csdnimg.cn/img_convert/ad7910fc0388e31a3fc0f44cfee498ec.png)
②explain select * from emp where age=45 order by deptid asc, name desc ;
如果排序的字段,顺序有差异,就需要将差异的部分,进行一次倒置顺序,因此还是需要手动排序的!