跳至主要內容

InnoDB的主键和二级索引树

张威大约 2 分钟mysqlmysql索引

InnoDB的主键和二级索引树

主键

  • 主键树中叶子节点key是主键值,data是主键所在行的数据
select * from student; #在有序链表中进行全文搜索
select * from stduent where uid=5; #等值搜索,从根节点开始在B+树上进行二分搜索
select * from stduent where uid<5; #范围查询,在有序链表中查找
select * from stduent where name='liuxiang'; #没有索引,在有序链表上进行整表搜索
image-20240418162100913
image-20240418162100913

二级索引

select name from student where name='liuxiang';
select uid,name from student where name='liuxiang';
select * from student where name='liuxiang'; #回表

回表的过程

练习

select * from student where age=20 order by name;

Q:name现在是索引,如果只给age添加索引行不行?还有什么没考虑得到呢?

A:不行,由于一张表一次sql查询只能用一个索引,之创建age键索引,会有Using filesort!!需要创建age,name的多列索引(先按age排序,age相同再按name排序)

  • 遇到外部排序Using filesort一定要优化