您的位置:首页 > 数据库

sql中索引优化查询效率的总结

2017-07-24 16:43 323 查看
在数据库中,对字段建立索引可以大大提高查询速度。

创建一个测试表testtb,并且向表中插入30万条记录。

create table testtb(id int not null, name varchar(10) not null, age int not null);

查看表中索引的方法:

show index from testtb;

show keys from testtb;

创建普通索引:

create index id_index on testtb(id);

alter table testtb add index id_index (id);

create table testtb(id int not null, name varchar(10) not null, age int not null, index id_index (id));

创建unique索引:

create unique index id_index on testtb(id);

alter table testtb add unique id_index(id);

create table testtb(id int not null, name varchar(10) not null, age int not null, unique index id_index (id));

创建primary key索引:

alter table testtb add primary key (id);

create table testtb(id int not null primary key , name varchar(10) not null, age int not null);

删除索引的方法:

drop index id_index on testtb;

alter table testtb drop index id_index;

删除primary key索引:

alter table testtb drop primary key;

一:无索引情况下

在没有建立索引的时候,查询记录语句explain select * from testtb where id = 200000;此时受影响的行有300000行,需要扫描全部记录。



二:创建普通索引

创建普通索引的情况下:

create index id_index on testtb(id);

再次使用查询记录语句,此时受影响的行只有1行,不需要扫描,即可找到该记录。



三:唯一索引

索引列的值必须唯一,不允许有空值。如果是组合索引,则组合的列值必须是唯一的。

四:组合索引

create index id_name_index on testtb(id,name);

如果分别在id, name上建立单列索引,查询时和组合索引相比,效率也会不大一样,mysql只会用到其中的一个认为最有效的单列索引。

建立组合索引(id, name)相当于建立了(id,name), (id)两种索引。索引组合是从最左面开始组合的(所以没有(name)这个索引)。

此时使用以下语句会用到联合索引,提高查询效率

explain select * from testtb where id=200000 and name =’kobe200000’;



explain select * from testtb where id=200000;



使用单独查询name时不会用到联合索引,

explain select * from testtb where name =’kobe200000’;



五:建立索引的选择

一般在where和join中出现的列需要建立索引。

Mysql只对<,>,<=,>=,=,between,in以及某些时候的like这些情况下使用索引。

使用like的情况:

在以通配符%和_开头查询时,mysql不会使用索引。

六:索引的缺点

1:索引会降低更新表的速度,如果对表进行Insert,update和delete操作,需要更新表,此时,Mysql不仅需要保存数据,还需要保存一下索引文件。

2:建立索引会占用磁盘空间的索引文件。如果在一个大表上创建多个组合索引,会导致索引文件很大。

不能滥用索引,尽量建立最优的索引组合。

七:注意事项:

1:索引不会包含有NULL值的列

只要列中包含有NULL值都将不会被包含在索引中,复合索引中只要有一列含有NULL值,那么这一列对于此复合索引就是无效的。所以我们在数据库设计时不要让字段的默认值为NULL。

2:使用短索引

对串列进行索引,如果可能应该指定一个前缀长度。例如,如果有一个CHAR(255)的列,如果在前10个或20个字符内,多数值是惟一的,那么就不要对整个列进行索引。短索引不仅可以提高查询速度而且可以节省磁盘空间和I/O操作。

3:索引列排序

MySQL查询只使用一个索引,因此如果where子句中已经使用了索引的话,那么order by中的列是不会使用索引的。因此数据库默认排序可以符合要求的情况下不要使用排序操作;尽量不要包含多个列的排序,如果需要最好给这些列创建复合索引。

4:like语句操作

一般情况下不鼓励使用like操作,如果非使用不可,如何使用也是一个问题。like “%aaa%” 不会使用索引而like “aaa%”可以使用索引。

5:不要在列上进行运算

select * from users where YEAR(adddate)<2007;

将在每个行上进行运算,这将导致索引失效而进行全表扫描,因此我们可以改成:

select * from users where adddate<‘2007-01-01’;

6:不使用NOT IN和<>操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息