MySQL学习--MySQL创建索引的若干总结
1、首先我们先看一下MySQL如何帮助我们自动创建索引,使用下述SQL语句创建一个表(注意这个语句中声明了主键列):
create table test_index (
id int not null auto_increment,
name varchar(100),
primary key (id)
) engine = innodb charset = utf8;
我们通过 primary key 指定了该表的主键,MySQL 也会基于该主键自动为我们创建聚簇索引!
表创建完毕后,可以通过 show index from 表名称 查看该表关联的所有索引信息。
2、再看另一种情况,我们不指定主键列,同样执行下面的建表语句:
create table test_index1 (
id int not null,
name varchar(100)
) engine = innodb charset = utf8;
从实际运行效果上看,MySQL不会为我们创建任何索引,但实际情况是,MySQL会为我们的表插入一个隐藏列rowid作为主键列,并基于该列创建聚簇索引,但该列和索引信息对用户都是不可见的。
3、继续,我们这次建表时,依然不指定主键,但我们指定一个 unique 列 (唯一约束):
create table test_index2 (
id int not null,
name varchar(100),
unique (name)
) engine = innodb charset = utf8;
从运行结果上看,MySQL还是会基于具有唯一约束的列 name 为我们创建索引(其本质也是为了当我们插入数据时,能最快判断是否有唯一性冲突),因为该列不是非空列,因此不能被选定为主键列,因此该索引是一个辅助索引而不是聚簇索引!
4、如果我们既指定了主键,又指定了唯一列,会是什么情况呢:
create table test_index3 (
id int not null,
name varchar(100),
unique(name),
primary key (id)
) engine = innodb charset = utf8;
从运行结果上看,MySQL会为主键列和唯一列都创建索引,主键列对应的是聚簇索引,唯一列对应的是辅助索引。
5、总结:MySQL首先会为选定的主键列自动创建聚簇索引,对于具有唯一约束的列,也会自动为其创建辅助索引。
1、上面说的都是MySQL为我们自动创建索引,那如何手动创建索引呢?
首先我们可以在建表语句中通过 key 索引名称 (列名称) 来创建索引:
create table test_index4 (
id int,
name varchar(100),
key idx_name (name)
) engine = innodb charset = utf8;
2、表建完后,我们也可以通过 create index 命令为表创建索引:
create table test_index5 (
id int,
name varchar(100)
) engine = innodb charset = utf8;
然后运行如下命令为表创建索引:
create index idx_name on test_index5(name)
3、总结:手动创建索引有两种方式,一是在创建表时通过 key 命令直接创建,二是表创建完毕后,通过 create index 语句创建。