【发布时间】:2010-11-29 06:41:26
【问题描述】:
假设我有下表(我们称之为my_table):
CREATE TABLE `my_table` (
`table_id` int(10) unsigned NOT NULL auto_increment,
`my_field` int(10) unsigned NOT NULL default '0'
PRIMARY KEY (`table_id`),
KEY `my_field` (`my_field`,`table_id`)
) ENGINE=MyISAM
my_table 的主键是 table_id (auto_increment),我还有一个带有 my_field 和 table_id 的键。
如果我测试这个查询...
EXPLAIN SELECT * FROM my_table
WHERE my_field = 28
ORDER BY table_id DESC;
...我明白了:
id select_type table type possible_keys key key_len ref rows Extra --- ----------- -------- ---- ------------- -------- --- ---- ----- ---- ----- 1 简单的 my_table 参考 my_field my_field 8 const 36您可以看到它使用了正确的密钥 (my_field)。
但如果我试试这个...
EXPLAIN SELECT * FROM my_table
WHERE my_field IN (1, 28, 20)
ORDER BY table_id DESC;
...我明白了:
id select_type table type possible_keys key key_len ref rows Extra --- ----------- -------- ---- ------------- ------ ----- -- ------ ---- --------------- 1 SIMPLE my_table ALL my_field (NULL) (NULL) (NULL) 406 使用 where;使用文件排序您可以看到它根本没有使用任何键,更糟糕的是,使用了 filesort。
即使我执行“FORCE INDEX (my_field)”,它仍然会执行文件排序。
有什么办法可以避免文件排序?
【问题讨论】:
-
更新了我的答案。派生表可能会对您有所帮助。
标签: sql mysql performance filesort