索引
1.概述
索引能提升 select语句的执行效率,用空间换取时间
当没有索引时:
执行select * from news where id = 9; 会进行全盘扫描,依次匹配是否相等,并且对于主键约束、唯一性约束的字段即使查找到了也会扫描到表尾
当创建索引后: 会形成索引的数据结构,比如二叉树
索引也会占用空间,使表的内存更大。同时对 dml(insert、delete、update)语句的效率有影响
2.分类
a.主键索引
主键索引,创建主键约束(primary key)时会自动创建主键索引
b.唯一索引 (UNIQUE)
唯一索引,创建唯一性约束(unique key)时会自动创建唯一索引
c.普通索引 (INDEX)
使用最多的
d.全局索引
一般Mysql中不使用全文索引,而是使用:全文搜索
Solr ElasticSearch (ES)
3.使用
a.查询索引:
show index from t01;
b.添加索引:
alter table add primary key (id); #主键索引
create unique index id_index on t01 (id); #唯一索引
create index id_index on t01 (id); #普通索引
c.删除索引:
drop index id_index on t01;
--
alter table t01
drop primary key; #主键索引
--
alter table
drop index 索引名; #唯一索引,普通索引(同时也是删除唯一性约束、外键约束的方式)
小结:哪些列上适合使用索引:
- 1.较频繁的作为查询条件字段应该创建索引
select from emp where emno 1- 2.唯一性太差的字段不适合单独创建索引,即使频繁作为查询条件
select from emp where sex = ‘男’- 3.更新非常频繁的字段不适合创建索引
select from emp where logincount 1- 4.不会出现在VHERE子句中字段不该创建索引