标签:
表结构信息:
mysql> show create table tb\G
*************************** 1. row ***************************
Table: tb
Create Table: CREATE TABLE `tb` (
`c` int(11) DEFAULT NULL,
`d` int(4) DEFAULT NULL,
`e` varchar(1000) DEFAULT NULL,
KEY `c` (`c`),
KEY `c_2` (`c`,`d`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
表中的数据:
mysql> select * from tb;
+------+------+------+
| c | d | e |
+------+------+------+
| 2 | 40 | b |
| 1 | 10 | a |
| 2 | 30 | a |
| 1 | 10 | a |
| 3 | 30 | a |
| 1 | 10 | c |
| 1 | 50 | c |
| 2 | 50 | c |
+------+------+------+
8 rows in set (0.00 sec)
测试order by,竟然没有走上索引
mysql> explain select * from tb where c > 1 order by c;
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------+
| 1 | SIMPLE | tb | ALL | c,c_2 | NULL | NULL | NULL | 8 | Using where; Using filesort |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------+
1 row in set (0.00 sec)
使用强制索引,情况是下面这样的。这里应该是MySQL优化器的bug
mysql> explain select * from tb force index (c) where c > 1 order by c;
+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | tb | range | c | c | 5 | NULL | 4 | Using where |
+----+-------------+-------+-------+---------------+------+---------+------+------+-------------+
1 row in set (0.00 sec)
order by 优化的一些规则:
• KEY(A,B)
• Will use Index for Sorting
– ORDER BY A - sorting by leading column
– A=5 ORDER BY B - EQ filtering by 1st and sorting by 2nd
– ORDER BY A DESC, B DESC - Sorting by 2 columns in same order
– A>5 ORDER BY A - Range on the column, sorting on the same
• Will NOT use Index for Sorting
– ORDER BY B - Sorting by second column in the index
– A>5 ORDER BY B – Range on first column, sorting by second
– A IN(1,2) ORDER BY B - In-Range on first column
– ORDER BY A ASC, B DESC - Sorting in the different order
标签:
原文地址:http://www.cnblogs.com/yuyue2014/p/4337956.html