建表语句和初始化数据如下:
-- test表a为主键
create table test (
a int not null,
b varchar(50),
c int not null,
primary key(a)
) engine=INNODB;
insert into test values
(1,'a',11),
(2, 'b', 12),
(3, 'c', 13),
(4, 'd', 14);
-- 创建联合索引 bc
ALTER TABLE test ADD index(b,c);
EXPLAIN select * from test where b='a';
EXPLAIN select * from test where c=11;
EXPLAIN select * from test where b='a' and c=11;
EXPLAIN select * from test where b='a' order by c;
EXPLAIN select * from test where c=11 order by b;
EXPLAIN select * from test where c=11 and b='a';
修改表结构
ALTER TABLE test ADD COLUMN d VARCHAR(50) NULL;
update test set d='22323';
EXPLAIN select * from test where c=11;
EXPLAIN select * from test where c=11 order by b;
为什么不一样?两个概念
回表和覆盖索引:在没有加d列时,b、c是联合索引,a是主键,这3列都在这个联合索引数据块中,所有数据都在刻意在索引中查找,就不需要回表查询,所以type是index(全索引扫描)。当加入列d时,所查找的数据包括d,需要回表查询,索引type是all(全表扫描)。