一.索引类型
innodb存储引擎支持索引类型:B+树索引,全文索引,哈希索引
innodb存储引擎哈希索引是自适应的,不能人工干预是否生成一张哈希索引
二.二叉查找树和平衡二叉树
三.b+树索引类型
聚集索引
表中的数据是按主键顺序存放
聚集索引就是按照每张表主键构成一颗B+树,同时叶子结点存放整张表的行记录数据。在多数情况下查询优化器倾向于采用聚集锁引,因为每张表能查询整行数据
辅助索引
辅助索引也称为非聚集索引
辅助索引查找数据key为索引列,value对应数据主键
当通过辅助索引来查询数据,mysql会遍历辅助索引并通过叶级别指针来获取指向主键,然后再通过主键索引来找到对应的行
联合索引
联合索引是对多列进行索引,联合索引和单个索引创建一样,不同有多个索引列
最左匹配原则
create table test3(
a int not null,
b int Null,
key(a),
key index_a_b(a,b)
);
insert into test3 select 11,1;
explain select * from test3 where a=10 and b=10;//中索引
explain select * from test3 where b=10 and a=10;//中索引,mysql优化器自动转select * from test3 where a=10 and b=10
explain select * from test3 where b=10 ;//不中索引,全表扫描
explain select b from test3 where a=100 order by b limit 3 ;//中联合索引,且不需要外部排序
explain select b from test3 force index(a) where a=100 order by b limit 3 ;//中索引a,使用外部排序
explain select count(*) from test3 ;//使用覆盖索引不需要查全部数据,只要查索引列,不查询数据列
覆盖索引
create table test4(
a int not null,
b int not Null,
primary key(a),
key b(b)
);
insert into test4 select 11,1;
explain select count(*) from test4 ;//使用覆盖索引选择索引b ,不查询数据列
四.sql建议
当我们写updtate或delete语句不是更新条件或删除主键或唯一索引时且是更新单行建议在where后加limit 1
当我们查询数据为枚举类别,如性别,建议不要建索引,查询也起不到作用
在没有唯一索引情况下,建议主键id设为自增,这样会提高插入效率
不用offset,当offet很大查询效率会很低