当前位置: 移动技术网 > IT编程>数据库>Mysql > 正确理解Mysql中的列索引和多列索引

正确理解Mysql中的列索引和多列索引

2017年12月12日  | 移动技术网IT编程  | 我要评论

mysql数据库提供两种类型的索引,如果没正确设置,索引的利用效率会大打折扣却完全不知问题出在这。

create table test (
  id     int not null,
  last_name char(30) not null,
  first_name char(30) not null,
  primary key (id),
  index name (last_name,first_name)
);

以上创建的其实是一个多列索引,创建列索引的代码如下:

create table test (
  id     int not null,
  last_name char(30) not null,
  first_name char(30) not null,
  primary key (id),
  index name (last_name),
   index_2 name (first_name)
);

一个多列索引可以认为是包含通过合并(concatenate)索引列值创建的值的一个排序数组。 当查询语句的条件中包含last_name 和 first_name时,例如:

select * from test where last_name='kun' and first_name='li';

sql会先过滤出last_name符合条件的记录,在其基础上在过滤first_name符合条件的记录。那如果我们分别在last_name和first_name上创建两个列索引,mysql的处理方式就不一样了,它会选择一个最严格的索引来进行检索,可以理解为检索能力最强的那个索引来检索,另外一个利用不上了,这样效果就不如多列索引了。
 
但是多列索引的利用也是需要条件的,以下形式的查询语句能够利用上多列索引:

select * from test where last_name='widenius';
select * from test where last_name='widenius' and first_name='michael';
select * from test where last_name='widenius' and (first_name='michael' or first_name='monty');
select * from test where last_name='widenius' and first_name >='m' and first_name < 'n';

以下形式的查询语句利用不上多列索引:

select * from test where first_name='michael';
select * from test where last_name='widenius' or first_name='michael';

多列建索引比对每个列分别建索引更有优势,因为索引建立得越多就越占磁盘空间,在更新数据的时候速度会更慢。
另外建立多列索引时,顺序也是需要注意的,应该将严格的索引放在前面,这样筛选的力度会更大,效率更高。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网