1
首先,我創建表
tag
:MySQL的使用索引優化排序CREATE TABLE `tag` ( `id` smallint(6) NOT NULL AUTO_INCREMENT, `total` int(11) DEFAULT NULL, `total_question` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_sort` (`total`,`total_question`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
的mysql>
explain select * from tag order by total;
+----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+ | 1 | SIMPLE | tag | index | NULL | idx_sort | 10 | NULL | 1 | Using index | +----+-------------+-------+-------+---------------+----------+---------+------+------+-------------+
排序使用索引,而不是使用filesort。
當我添加列
name
到tag
表:CREATE TABLE `tag` ( `id` smallint(6) NOT NULL AUTO_INCREMENT, `total` int(11) DEFAULT NULL, `total_question` int(11) DEFAULT NULL, `name` char(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_sort` (`total`,`total_question`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
的MySQL>
explain select * from tag order by total;
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+------+----------------+ | 1 | SIMPLE | tag | ALL | NULL | NULL | NULL | NULL | 1 | Using filesort | +----+-------------+-------+------+---------------+------+---------+------+------+----------------+
排序使用文件排序,不使用索引。
當我創建的索引只
total
:CREATE TABLE `tag` ( `id` smallint(6) NOT NULL AUTO_INCREMENT, `total` int(11) DEFAULT NULL, `total_question` int(11) DEFAULT NULL, `name` char(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_sort` (`total`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
的mysql>
explain select * from tag order by total;
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+------+---------------+------+---------+------+------+----------------+ | 1 | SIMPLE | tag | ALL | NULL | NULL | NULL | NULL | 1 | Using filesort | +----+-------------+-------+------+---------------+------+---------+------+------+----------------+
排序使用文件排序!爲什麼?我只使用
total
列進行排序。
因爲選擇'*' - '*'就是全部,而指數裏只含有總的值,因爲,你是隻索引總列,所以,如果你正在做'選擇從標籤順序總數'< - 這將不會觸發filesort – ajreal 2012-03-19 11:19:38
我認爲你不能如果你想在單個查詢中有所有列返回 – ajreal 2012-03-19 11:49:15
什麼如果你沒有選擇最後一個版本表中的所有列,會發生什麼?從標籤順序總數中選擇id,total,total_question; – 2012-03-19 12:13:48