MySQL之order by优化

发布时间 2023-07-21 17:43:30作者: 镰刀战士

MySQL之order by优化

  1. .Using filesort:通过表的索引或全表扫描,读取满足条件的数据行,然后在排序缓冲区sort buffer中完成排序操作,所有不是通过索引直接返回排序结果的排序都叫 FileSot 排序。

  2. Using index:通过有序索引顺序扫描直接返回有序数据,这种情况即为 using index,不需要额外排序,操作效率高。

 #没有创建索引时,根据age, phone进行排序
 explain select id,age,phone from tb_user order by age , phone;
 #创建索引
 create index idx user age phone aa on tb_user(age,phone):
 #创建索引后,根据age,phone进行升序排序
 explain select id,age,phone from tb_user order by age , phone;
 #创建索引后,根据age,phone进行降序排序
 explain select id,age,phone from tb_user order by age desc , phone desc;



因为创建值的时候都是升序排的。如下图




创建age asc , phone desc索引后,再查age asc和phone desc速度会变快


 #根据age,phone进行降序一个升序,一个降序
 explain select id,age,phone from tb_user order by age asc , phone desc;
 #创建索引
 create index idx user age_phone ad on tb_user(age asc ,phone desc);
 #根据age,phone进行降序一个升序,一个降序
 explain select id,age,phone from tb_user order by age asc , phone desc;


查找select * 时,*中有的没有建立索引,因此需要回表查询,性能降低,因此尽量使用覆盖查询,就是查询使用了索引,并且返回列在索引中都可以找到,不需要回表查询。


order by优化

  1. 根据排序字段建立合适的索引,多字段排序时,也遵循最左前缀法则。

  2. 尽量使用覆盖索引。

  3. 多字段排序,一个升序一个降序,此时需要注意联合索引在创建时的规则 (ASC/DESC)。

  4. 如果不可避免的出现filesort,大数据量排序时,可以适当增大排序缓冲区大小 sort_buffer_size(默认256k)。

 #查询缓冲区大小
 show variables like "sort_buffer_size';