mysql索引意义和价值

mysql索引意义和价值

下文内容主要给大家带来mysql索引意义和价值,这里所讲到的知识,与书籍略有不同,都是亿速云专业技术人员在与用户接触过程中,总结出来的,具有一定的经验分享价值,希望给广大读者带来帮助

索引存在的意义:

一般来说,加了索引之后,可以提高访问数据库表的速度,查询会更快。

更有利于select语句提高性能


不要过度索引。

并不是只要加了索引就会提升性能,有可能起反作用。

mysql索引意义和价值

什么样的字段适合创建索引,一般来说:

  1. 主键

  2. 经常需要排序的列

  3. 经常使用在where子句中的列


什么样的字段不适合创建索引,一般来说:

  1. 很少数据值的列(比如性别,只有2个值,非男即女)

  2. 字段类型text、image、bit (这些都是大字段,数据量比较大)

  3. 当修改远远大于搜索的时候(update操作多,select操作少)


几种不同的索引:

主键索引

规则:索引列不能包含重复值,且不能为空

alter table 表1 add primary key(列1[,列2])


普通索引

没有规则

alter table 表1 add index 索引名(列1[, 列2])

create index 索引名 on 表1(列1[, 列2])

举例:

alter table person_info add index myindex(salary)

alter TABLE person_info add index hisindex(name, salary)

create index yourindex on person_info(salary)

create index herindex on person_info(salary, name)


唯一索引

规则:索引列的值必须唯一,但可以为空

alter table 表1 add unique index 索引名(列1[, 列2])

create unique index 索引名 on 表1(列1[, 列2])



查看索引

show index from 表1

desc 表1   查看表结构也能看出来

举例:

show index from person_info

desc 表1


索引的删除

drop index 索引名 on 表1

drop index yourindex on person_info



单索引和组合索引

单索引:

alter table person_info add index myindex(salary)

alter table person_info add index myindex(name)

组合索引

alter TABLE person_info add index hisindex(name, salary)

备注: 

组合索引的效率要比单索引高,但也跟数据量有关,数据多的话对比才明显

对于以上关于mysql索引意义和价值,如果大家还有更多需要了解的可以持续关注我们亿速云的行业推新,如需获取专业解答,可在官网联系售前售后的,希望该文章可给大家带来一定的知识更新。