哈希空间

mysql联合索引

联合索引

MySQL中可以对多个字段建立联合索引,作用是当where 多条件查询时,使用更高效率的索引,扫描更少的行数。

新建联合索引

对 学生信息表 student 中的 身高 height 生日 birthday 姓名 name 建立联合索引 height_birthday_name

alter table student add index height_birthday_name(height,birthday,name)

联合索引使用条件

联合索引遵循从到右的匹配顺序,顺序一致时可以也可以实现索引查询。
比如下面的语句都可以命中索引实现加速查询

select * from student where height=180; select * from student where height>=180; select * from student where height>=180 and birthday>='1990-01-01'; select * from student where height>=180 and birthday>='1990-01-01' and name='Jack';

跳过或缺失顺序中的字段,则无法使用该联合索引加速查询。比如不使用 height 作为条件,仅使用 birthday 或 name 则无法命中索引。必须严格前缀匹配 height, birthday,name 才能命中索引。

下面是无法使用该联合索引的查询语句:

select * from student where birthday>='1990-01-01'; select * from student where birthday>='1990-01-01' and name='Jack'; select * from student where name='Jack'; select * from student where height>=180 and name='Jack';

查看 sql 使用索引情况,查询数据库执行计划

explain select * from student where birthday>='1990-01-01'

其中 key 会显示使用的索引,更多可以参考 mysql查看执行计划mysql explain 用法详解

建立多种索引

一个表中可以建立多种索引,包括多个联合索引来实现查询加速。但是需要注意的是 表中索引过多时会引发 数据更新写入性能的下降。这种情况在更新 几百万行以上的大表时显得尤为明显,可能会直接导致数据库卡死、失去响应。对于大表更新时应该每次更新一小部分记录,分时完成数据更新。

本文 最佳观看地址:https://www.hashspace.cn/mysql-lianhesuoyin.html 阅读 580

打开 哈希空间 微信小程序中查看更佳