Chinaunix首页 | 论坛 | 博客
  • 博客访问: 8172
  • 博文数量: 1
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 12
  • 用 户 组: 普通用户
  • 注册时间: 2015-01-03 14:17
文章分类

全部博文(1)

文章存档

2015年(1)

我的朋友
最近访客

分类: Mysql/postgreSQL

2015-01-05 10:43:18

创建一个使用列索引的表:
 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';  

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

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


阅读(922) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:没有了

给主人留下些什么吧!~~