让's suppose I have the following table (let' s称之为 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 SIMPLE my_table ref 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 Using where; Using filesort
您可以看到它根本没有使用任何密钥,更糟糕的是,使用 filesort .
即使我做“ FORCE INDEX (my_field) ”,它仍然执行filesort .
有没有办法避免filesort?