操作
添加
-
创建时添加 主键,唯一
index idx_age(age) -
创建后添加
add index idx_age_location(age,location); -
控制顺序(默认asc升序)
idx_age(age,desc)
删除
- alter table test drop index location;
隐藏索引
- 在有时会删除索引来提高性能,如果没有提高还要再添加回来,隐藏索引可以让索引失效。
- 主键不能使用隐藏索引
- 设置
alter table test alter index invisible/visible
适合添加的10种情况
- where
- distinct
- group by , order by
- join
- 字段有唯一的限制
- 区分度高,散列性高
- 占用空间小的类型作为索引
- varchar用前缀 前缀数最好让count(distinct left(location,前缀数))/count(*) 接近1
- 将常用索引放在联合索引左侧
- 如果多个索引都要使用,联合索引优于单索引
不适合索引的6中情况
- 区分度低(比如性别)
- 占用空间大的类型
- 表的数据量小
- where用不到
- 不要创建冗余索引(联合和单)或者重复索引
- 不建议对无序的列添加索引(非单调,数据转移)
- 经常更新的表不要添加过多索引(索引维护)