日期:2014-05-16  浏览次数:20908 次

MySQL 优化索引 —— Using filesort
用Explain分析SQL语句的时候,经常发现有的语句在Extra列会出现Using filesort,根据mysql官方文档对他的描述:

引用
MySQL must do an extra pass to find out how to retrieve the rows in sorted order. The sort is done by going through all rows according to the join type and storing the sort key and pointer to the row for all rows that match the WHERE clause.

中文手册上翻译的很别扭:

引用
“Mysql需要额外的一次传递,以找出如何按排序顺序检索行,通过根据联接类型浏览所有行并为 所有匹配where子句的行保存排序关键字和行的指针来完成排序,然后关键字被排序,并按排序顺序检索行。”


总的来说,Using filesort 是Mysql里一种速度比较慢的外部排序,如果能避免是最好的了,很多时候,我们可以通过优化索引来尽量避免出现Using filesort,从而提高速度。

这里举个简单的例子:

CREATE TABLE `testing` (
`id` int(10) unsigned NOT NULL auto_increment,
`room_number` int(10) unsigned NOT NULL default '0',
PRIMARY KEY   (`id`),
KEY `room_number` (`room_number`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1


写个存储过程askwan,插入10万条测试数据

mysql> DELIMITER $$
DROP PROCEDURE IF EXISTS `askwan`.`askwan` $$
CREATE PROCEDURE `askwan`.`askwan` ()
BEGIN
DECLARE v INT DEFAULT 1;
WHILE v<100000;
DO
INSERT INTO testing VALUES(v,v);
SET v=v+1;
END WHILE;

END $$
mysql> DELIMITER ;
mysql> CALL askwan();
Query OK, 1 row affected (13.21 sec)


OK,数据准备好了,开始试验。

由上面例子中建立的表信息,我已经建立了两个索引,一个主键id,一个 room_number列索引
那现在来看一条SQL,

SELECT id FROM testing WHERE room_number=1000 ORDER BY id ;


分析一下

mysql> EXPLAIN SELECT id FROM testing WHERE room_number=1000 ORDER BY id ;+----+-------------+---------+------+---------------+-------------+---------+-------+------+-----------------------------+| id | select_type | table     | type | possible_keys | key           | key_len | ref     | rows | Extra                         |+----+-------------+---------+------+---------------+-------------+---------+-------+------+-----------------------------+|    1 | SIMPLE        | testing | ref    | room_number     | room_number | 4         | const |      1 | Using where; Using filesort | +----+-------------+---------+------+---------------+-------------+---------+-------+------+-----------------------------+1 row in set (0.00 sec)

出现了Using filesort,并且用到了room_number这列索引,但是,在这里用到的索引是针对WHERE后面的room_number条件的,而最后面的 排序是根据id来的,这就是手册中说的,“额外的一次排序”!,于是就会出现Using filesort,根据我以前写过的一文章,我再建立一个联合索引 room_number_id

alter table testing add index room_number_id(room_number,id);
在来分析一下

mysql> EXPLAIN SELECT id FROM testing WHERE room_number=1000 ORDER BY id ;+----+-------------+---------+------+----------------------------+----------------+---------+-------+------+--------------------------+| id | select_type | table     | type | possible_keys                | key              | key_len | ref     | rows | Extra                      |+----+-------------+---------+------+----------------------------+----------------+---------+-------+------+--------------------------+|    1 | SIMPLE        | testing | ref    | room_number,room_number_id | room_number_id | 4         | const |      1 | Using where;    | +----+-----------