Welcome 微信登录

首页 / 数据库 / MySQL / order by多个字段对索引的影响

某前台sql语句,简化后如下
SELECT products_name,products_viewed FROM `products_description`
ORDER BY products_viewed DESC,products_name LIMIT 0,20;该语句经常大批量出现在慢日志中!初步看改语句,非常简单,根据products_viewed(产品被查看次数)倒序排序,再根据products_name(产品名字)排序!在products_viewed和products_name上分别建立有索引!
但是感觉products_name排序怪怪的!
explain后发现
+----+-------------+----------------------+------+---------------+------+---------+------+-------+----------------+
| id | select_type | table                | type | possible_keys | key  | key_len | ref  | rows  | Extra          |
+----+-------------+----------------------+------+---------------+------+---------+------+-------+----------------+
|  1 | SIMPLE      | products_description | ALL  | NULL          | NULL | NULL    | NULL | 764370 | Using filesort |
+----+-------------+----------------------+------+---------------+------+---------+------+-------+----------------+改语句做竟然全表扫描!mysql的order by语句,如果在where条件中没有合适的索引选择时,将会选择order by col中的索引作为条件,但是如果是多个order by组合,将会导致放弃使用索引!
和开发以及需求沟通,发现通过名字排序是可以不需要的!
我们去掉order by后面的 products_name!
再次explain后发现已经能够使用索引:
explain SELECT products_name,products_viewed FROM `products_description`
 ORDER BY products_viewed LIMIT 0,20;
+----+-------------+----------------------+-------+---------------+-----------------+---------+------+------+-------+
| id | select_type | table                | type  | possible_keys | key           | key_len | ref  | rows | Extra |
+----+-------------+----------------------+-------+---------------+-----------------+---------+------+------+-------+
|  1 | SIMPLE      | products_description | index | NULL          | products_viewed | 5     | NULL | 20 |     |
+----+-------------+----------------------+-------+---------------+-----------------+---------+------+------+-------+再次对比两次profiling(过程省略),发现第一次损坏大量io和cpu时间Sorting result上!因为该语句为前台语句,有大量查询,优化后,页面打开速度明显提升!注意:
1. order by m,n  不要轻易写这种语句,一般的order by前面的m才是order by的重点,后面的n为配角,如果没有必要,尽量去掉
2. 参考我的另一篇 http://www.linuxidc.com/Linux/2014-03/98549.htm不要随随便便的distinct和order by减少不必要的group by字段相关资讯      Order By 
  • MySQL 强制操作以及order by 使用  (04月20日)
  • MySQL优化order by导致的 using   (11/06/2015 14:32:26)
  • 关于order by的一些用法  (04/17/2015 09:16:35)
  • MySQL中order by 结果不准确的问题  (11/11/2015 12:14:35)
  • Oracle update和order by  (07/24/2015 10:28:59)
  • MySQL新旧版本ORDER BY 处理方法  (06/24/2014 15:18:10)
本文评论 查看全部评论 (0)
表情: 姓名: 字数