创建表,以及联合索引 b_c_d
CREATE TABLE tab_test
(
id
int(11) NOT NULL,
a
int(11) NOT NULL,
b
int(11) NOT NULL,
c
varchar(255) NOT NULL,
d
int(11) NOT NULL,
PRIMARY KEY (id
),
KEY idx_b_c_d
(b
,c
,d
) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
能命中的索引情况。
//【左匹配】,b_c_d 索引
1 explain select * from tab_test where b = 1;
2 explain select * from tab_test where b = 1 and c= ‘e’; //交换 b,c 的位置,也能命中索引,应
为查询优化器会交换他们的位置。
3 explain select * from tab_test where c= ‘e’ and b = 1 and d= 1;
//【左匹配+其它字段】也能命中 b_c_d 索引。
1 explain select * from tab_test where b = 1 and a=6;
2 explain select * from tab_test where b = 1 and c= ‘e’ and a=6;
3 explain select * from tab_test where c= ‘e’ and b = 1 and d= 1 and a = 1;
//【左匹配+排序】
总结:
1 左匹配+左匹配排序字段 (排序字段也必须是左匹配的)
1 explain select * from tab_test where b > 8 and c = ‘e’ and d >5 order by b asc, c asc, d asc;
3 explain select * from tab_test where b > 8 order by b asc;
4 explain select * from tab_test where b > 8 order by b desc;
5 explain select * from tab_test where b > 8 and c = ‘e’ and d < 5 order by b asc;
2 左匹配+排序字段对应的都是常量
explain select * from tab_test where b > 8 and c = ‘e’ and d > 9 order by c asc; //排序字段只有 c
但 是 c 字 段 只 查 出 常 量 。
以下不能命中索引
排序字段,不是左匹配,则会使用文件排序。