这种为啥走索引
楼主你好,这个问题涉及两方面:
先说下结论,mysql对order by + where 的情况做了优化,能走索引,
但是 type = index 属于全索引扫描,性能排倒数第二。
分析 explain 的结果
type = index
extra = using index
在 https://dev.mysql.com/doc/refman/8.0/en/explain-output.html#explain-join-types 中说明如下,
走了全索引扫描,且数据都在索引中。效率上排倒数第二,仅比全表扫描好一点儿
关于 extra = Using where,
在 https://dev.mysql.com/doc/refman/5.7/en/explain-output.html#explain_extra 中说明如下:如果不想全表查询但是 type = index 或 ALL时,查询可能出了问题。
关于 order by:下面是5.7 和 8.0两个版本
https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html
https://dev.mysql.com/doc/refman/8.0/en/order-by-optimization.html#order-by-index-use
里面提到:order by + where 涉及多个字段时可以使用复合索引(key_part1, key_part2)进行优化
回到楼主的sql,如果您想看详细的优化过程可以打开optimizer_trace 优化器追踪器,
-- 查询优化器追踪是否开启:
show variables like 'optimizer_trace%';
-- 打开优化器追踪
set optimizer_trace='enabled=on '
-- 执行完一条语句之后执行下面语句查看优化器追踪:
select * from information_schema.optimizer_trace\G
相关资料:
https://www.cnblogs.com/peteremperor/p/13559480.html
https://dev.mysql.com/doc/internals/en/optimizer-tracing.html