索引分类

目前MySQL支持的索引有:

由于索引是在存储引擎层实现的,所以不同的存储引擎的索引实现会有一些差异。

InnoDB的不同的索引组织结构以及索引触发条件

如果索引键值逻辑顺序与索引所服务的表中相应行的物理顺序相同,那么该索引被称为簇索引(cluster index),也称为聚集索引、聚簇索引,也就是说数据和索引(B+树)在一起,记录被真实地保存在索引的叶子中,簇索引也称为索引组织表,反之为非聚集索引。

聚簇索引/主键索引

create table workers
 (
     id    int(11)     not null auto_increment comment '员工工号',
     name  varchar(16) not null comment '员工名字',
     sales int(11) default null comment '员工销售业绩',
     primary key (id)
 ) engine InnoDB
   AUTO_INCREMENT = 10
   default charset = utf8;
 
 insert into workers(id, name, sales)
 values (1, '江南', 12744);
 insert into workers(id, name, sales)
 values (3, '今何在', 14082);
 insert into workers(id, name, sales)
 values (7, '路明非', 14738);
 insert into workers(id, name, sales)
 values (8, '吕归尘', 7087);
 insert into workers(id, name, sales)
 values (11, '姬野', 8565);
 insert into workers(id, name, sales)
 values (15, '凯撒', 8501);
 insert into workers(id, name, sales)
 values (20, '绘梨衣', 7890);
 insert into workers(id, name, sales)
 values (21, '西泽尔', 6664);

聚簇索引的B+树:

Untitled

InnoDB表要求必须有聚簇索引,默认在主键字段上建立聚簇索引,在没有主键字段的情况下,表的第一个NOT NULL 的唯一索引将被建立为聚簇索引,在前两者都没有的情况下,InnoDB将自动生成一个隐式自增id列并在此列上创建聚簇索引。

二级索引

alter table workers add index  index_name(name); // 在name字段上添加二级索引index_name

二级索引的B+树:

Untitled