MySQL索引使用--最左前缀法则

验证索引效率

在未建立索引之前,执行如下SQL语句,查询SQL的耗时:

select * from tb_sku where sn='SN0003450001'

针对字段创建索引

create index idx_sku_sn on tb_sku(sn);

创建完索引之后,再来看这条查询sql的耗时。

查看sql的执行计划

最左前缀法则:

如果索引了多列(联合索引),要遵守最左前缀法则。最左前缀法则指的是查询从索引的最左列开始,并且不跳过索引中的列。如果跳跃某一列,索引将部分失效(后面的字段索引失效)。

sql 复制代码
-- 1. 查询profession、age、status三个条件
explain select * from tb_user where profession = '软件工程' and age = 31 and status = '0';

-- 2. 查询profession、age两个条件
explain select * from tb_user where profession = '软件工程' and age = 31;

-- 3. 仅查询profession条件
explain select * from tb_user where profession = '软件工程';

-- 4. 查询age、status两个条件(缺少profession)
explain select * from tb_user where age = 31 and status = '0';

-- 5. 仅查询status条件
explain select * from tb_user where profession = '软件工程' and status = '0';

tb_user表中的索引如下

最左前缀法则的验证:

a)执行

select * from tb_user where profession='软件工程' and age=31 and status='0';

可能使用的索引是 idx_pro_age_sta; 实际使用的索引是 idx_pro_age_sta;

b)执行

select * from tb_user where profession = '软件工程' and age = 31;

可能使用的索引是idx_pro_age_sta, 实际使用的索引是idx_pro_age_sta;idx_pro_age_sta;

c) 执行

select * from tb_user where profession = '软件工程';

可能使用的索引是idx_pro_age_sta, 实际使用的索引是idx_pro_age_staidx_pro_age_sta

d)执行

select * from tb_user where age = 31 and status = '0';

没有匹配的索引可以使用。

e)执行

select * from tb_user where profession = '软件工程' and status = '0';

索引的长度是43,说明只有profession字段使用到了索引; status字段的索引失效。

f)执行

select * from tb_user where age = 31 and status = '0' and profession = '软件工程';

索引长度是55,说明三个字段的索引都用上了。这说明字段在where条件中的位置无关。

范围查询,联合索引中,出现范围查询(>,

explain select * from tb_user where profession = '软件工程' and age > 30 and status ='0'; explain select * from tb_user where profession = '软件工程' and age >= 30 and status = '0';

age 使用了范围查询,age右边的列status会失效,因此索引的长度是48.

age 使用>=的范围查询时,age右边的列不会索引失效。

相关推荐
银发控、21 小时前
MySQL联合索引
数据库·mysql
予枫的编程笔记21 小时前
【MySQL修炼篇】从踩坑到精通:事务隔离级别的3大异常(脏读/幻读/不可重复读)解决方案
数据库·mysql·后端开发·数据库事务·事务隔离级别·rr级别·脏读幻读不可重复读
一起养小猫1 天前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
世界尽头与你1 天前
(修复方案)CVE-2023-22047: Oracle PeopleSoft Enterprise PeopleTools 未授权访问漏洞
数据库·安全·oracle·渗透测试
韩立学长1 天前
【开题答辩实录分享】以《智能大学宿舍管理系统的设计与实现》为例进行选题答辩实录分享
数据库·spring boot·后端
Henry Zhu1231 天前
数据库(五):反规范化
数据库
Mr_Xuhhh1 天前
MySQL函数详解:日期、字符串、数学及其他常用函数
java·数据库·sql
he___H1 天前
Redis高级数据类型
数据库·redis·缓存
霖霖总总1 天前
[小技巧60]深入解析 MySQL Online DDL:MySQL Online DDL、pt-osc 与 gh-ost 机制与最佳实践
数据库·mysql
爱学习的阿磊1 天前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python