您的位置:首页 > 博客中心 > 数据库 >

MySQL列索引与多列索引浅析

时间:2022-03-14 04:35

创建一个使用列索引的表:  create table index_test1(
id int not  null auto_increment,
first_name varchar(30) not null,
last_name varchar(30) not null,
primary key(id),
index index_first(first_name),
index index_last(last_name)
)engine myisam charset utf8;
创建一个使用多列索引的表:
create table more_index_test1(
id int not  null auto_increment,
first_name varchar(30) not null,
last_name varchar(30) not null,
primary key(id),
index index_first(first_name,last_name)
)engine myisam charset utf8;   一个多列索引可以认为是包含通过合并(concatenate)索引列值创建的值的一个排序数组。 当查询语句的条件中包含last_name 和 first_name时,例如:   select * from index_test  where first_name = ‘1‘ and first_name = ‘2‘;   sql会先过滤出last_name符合条件的记录,在其基础上在过滤first_name符合条件的记录。那如果我们分别在last_name和first_name上创建两个列索引,mysql的处理方式就不一样了,它会选择一个最严格的索引来进行检索,可以理解为检索能力最强的那个索引来检索,另外一个利用不上了,这样效果就不如多列索引了。 但是多列索引的利用也是需要条件的,以下形式的查询语句能够利用上多列索引: SELECT * FROM more_index_test1 WHERE first_name =‘1‘;
SELECT * FROM more_index_test1 WHERE first_name =‘1‘ AND first_name =‘2‘;
SELECT * FROM more_index_test1 WHERE first_name =‘1‘ AND (first_name =‘2‘ OR first_name =‘3‘);
SELECT * FROM more_index_test1 WHERE first_name =‘1‘ AND first_name >=‘2‘ AND first_name < ‘3‘; 但以下形式的查询不能使用多列索引:   select * from more_index_test1 where last_name = ‘1‘ ;   SELECT * FROM more_index_test1 WHERE last_name=‘1‘ OR first_name=‘2‘;  

多列建索引比对每个列分别建索引更有优势,因为索引建立得越多就越占磁盘空间,在更新数据的时候速度会更慢。

另外建立多列索引时,顺序也是需要注意的,应该将严格的索引放在前面,这样筛选的力度会更大,效率更高。

热门排行

今日推荐

热门手游