手机版
你好,游客 登录 注册
背景:
阅读新闻

order by多个字段对索引的影响

[日期:2014-03-20] 来源:Linux社区  作者:qdjalone [字体:大 中 小]

某前台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

linux
相关资讯       Order By 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款