orderBy命中索引时,会直接按照索引的顺序不需要再排序,但是如果没有命中索引,就需要额外的一个sort的过程,如果我们使用explain会看到extra列会有using file sort的提示。
示例.一个表只有id和name两个字断。
id为主键索引,name没有索引
1.按索引排序
explain select * from `user` order by id;
结果
(`id`, `select_type`, `table`, `partitions`, `type`, `possible_keys`, `key`, `key_len`, `ref`, `rows`, `filtered`, `Extra`)
(1, 'SIMPLE', 'user', NULL, 'index', NULL, 'PRIMARY', '4', NULL, 1, 100.00, NULL);
2.按照非索引列排序
explain select * from `user` order by `name`;
结果
(`id`, `select_type`, `table`, `partitions`, `type`, `possible_keys`, `key`, `key_len`, `ref`, `rows`, `filtered`, `Extra`)
(1, 'SIMPLE', 'user', NULL, 'ALL', NULL, NULL, NULL, NULL, 1, 100.00, 'Using filesort');