(20)索引类型、使用原则、利弊、增删查索引语法
索引:是针对数据所建立的目录
一、索引:二叉树、哈希
二、利弊
好处:加快了查询速度
坏处:降低了增删改的速度,增加了表饿文件大小(索引文件甚至可能比数据文件还大)
场景:换服务器导数据
sql
新闻表 500w行
table news
{
15列
10(索引)
}
方法:先删除索引,再导入数据,最后集中建索引
三、索引的使用原则
①不要过度索引
②索引条件列(where后面最频繁的条件比较适宜索引)
③索引散列值,过于集中的值不要索引(例如,给性别‘男’‘女’加索引,意义不大)
四、索引类型
普通索引(index):仅仅加快查询速度
唯一索引(unique index):行上的值不能重复
主键索引(primary key index):不能重复
全文索引:fulltext index
主键索引、唯一索引的区别:主键必唯一,但是唯一索引不一定是主键
一个表上,只能有一个主键,但是可以用一个或者多个唯一索引
五、查看一张表中的所有索引(以表形式显示)
show index from 表名\G
六、创建索引
alter table 表名 add index/unique/fulltext[索引名] (列名)
索引名可以不写,默认索引名和列名相同,因为一张表中,列不会重复,保证了索引的唯一性
alter table 表名 add primary key(列名)//不用加索引名,因为主键唯一
create table member(
id int,
email varchar(30),
tel char(11),
intro text)engine myisam charset utf8;
//普通索引(Index_type: BTREE)
alter table member add index tel(tel);
唯一索引(Index_type: BTREE)
alter table member add unique (email);
//全文索引 ( Index_type: FULLTEXT)
alter table member add fulltext (intro);
七、删除索引
删除非主键索引:alter table 表名 drop index 索引名;
删除主键索引:alter table 表名 drop primary key;
alter table member drop index tel;
alter table member drop index email;
alter table member drop index infor;
alter table member drop primary key;