1:条件中有or,并且所有条件字段都建了索引,才能用到索引,否则用不到。
explain select * from sdb_b2c_members where mobile='18202139749' or name = '邢进'
这条sql语句中的mobile和name都建了索引,所以用到了索引。
explain select * from sdb_b2c_members where mobile='18202139749' or point = '3034'
这条sql语句中的mobile字段有索引,但是point字段没索引,所以没用到索引。
所以:要想使用or,又想让索引生效,只能将or条件中的每个列都加上索引
2:对于多列索引,要遵循最左前缀原则,否则用不到索引(除非这个字段在多列索引之外又建立了单个索引)。
比如,我建了一个组合索引,索引顺序是:a b c d
where a = ‘’;//能用到索引
where a = ‘’ and b = ‘’ and c = ‘’ and d = ‘’;//能用到索引
where a = ‘’ and b=’’ and d = ‘’ //此时d用不到索引
where a = ‘’ and b > 10 //a能用到索引,b用不到
where b = ‘’ //用不到索引
建表:
CREATE TABLE student3(
id INT(11) auto_increment,
name VARCHAR(10) not null,
age int(10) not null default 0,
height int(10) not null default 0,
weight int(10) not null default 0,
primary key (id),
key n_a_h_w(name,age,height,weight)
)ENGINE=INNODB;
跳过联合索引的第一个字段name,直接用第二个字段:发现type列是index,表示进行了全索引扫描。
explain select * from student3 where age = 20;
+----+-------------+----------+------------+-------+------