Home > Database > Mysql Tutorial > body text

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

WBOY
Release: 2016-06-07 17:36:09
Original
1082 people have browsed it

初步看改语句,非常简单,根据products_viewed(产品被查看次数)倒序排序,再根据products_name(产品名字)排序!在products_vie

某前台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. 参考我的另一篇

linux

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template