结论,在abc三个字段的符合索引,只要用到了a这个字段,都能够使用索引,与顺序无关。
CREATE TABLE key_test (id int(11), name VARCHAR(20), priority int(4), desc VARCHAR(255));
EXPLAIN SELECT * FROM key_test WHERE id = 1 and priority = 1 AND name = 'xly';//a,c,b(使用索引)
EXPLAIN SELECT * FROM key_test WHERE priority = 1 AND name = 'xly' AND id = 1;//c,b,a(使用索引)
EXPLAIN SELECT * FROM key_test WHERE id = 1 and name = 'xly';//a,b(使用索引)
EXPLAIN SELECT * FROM key_test WHERE id = 1 and priority = 1;//a,c (使用索引)
EXPLAIN SELECT * FROM key_test WHERE priority = 1 AND id = 1;//c,a (使用索引)
EXPLAIN SELECT * FROM key_test WHERE priority = 1;//c (未使用索引)
EXPLAIN SELECT * FROM key_test WHERE name = 'xly';//b (未使用索引)
EXPLAIN SELECT * FROM key_test WHERE name = 'xly' AND priority = 1;//b,c(未使用索引)
EXPLAIN SELECT * FROM key_test WHERE priority = 1 AND name = 'xly';//c,b(未使用索引)
-- 使用order来排序
EXPLAIN SELECT * FROM key_test WHERE priority = 1 AND name = 'xly' ORDER BY id;//where c,b order a (未使用索引)
EXPLAIN SELECT id,name,priority FROM key_test ORDER BY id;//查询索引覆盖以外的字段,然后进行order by 会出现filesort
-- 给id添加主键索引
EXPLAIN SELECT * FROM key_test WHERE priority = 1 AND name = 'xly' ORDER BY id;//where c,b order a (使用主键索引)
EXPLAIN SELECT * FROM key_test WHERE priority = 1 AND name = 'xly' ORDER BY name;//where c,b order b (全表扫描,没有使用filesort)
EXPLAIN SELECT * FROM key_test WHERE priority = 1 AND name = 'xly' ORDER BY `desc`;//where c,b order d(全表扫描,使用filesort)