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右边的列不会索引失效。

相关推荐
阿正的梦工坊12 分钟前
【Rust】04-借用、引用与切片
java·数据库·rust
AOwhisky17 分钟前
学习自测与解析:MySQL第五、六、七期核心知识点详解
运维·数据库·笔记·学习·mysql·云计算
阿标在干嘛27 分钟前
政策平台的推送系统:消息队列、定时任务、AB测试的工程实践
服务器·数据库·ab测试
Upsy-Daisy37 分钟前
Hermes Agent 学习笔记 02:安装、配置与第一次运行
java·前端·数据库
Tongpao_SSDHDD1 小时前
希捷酷鹰ST6000VX008实测解析:中小安防监控高性价比存储方案
大数据·数据库·人工智能
蓝鸟19742 小时前
Oracle超大DMP备份文件瘦身、日志精简、磁盘空间优化实战方案日志
数据库·oracle·数据库运维·生产运维实战·oracle避坑·磁盘空间优化·oracle日志清理
梦想的旅途22 小时前
企业微信外部群主动调用:RPA 接口与官方 API 的技术边界
网络·mysql·自动化·企业微信·rpa
金融支付架构实战指南2 小时前
CQRS + 命令模式 + 事件驱动 + 数据库持久化
数据库·ddd·命令模式·领域驱动模型
sevenll072 小时前
DocKit agentic MongoDB GUI 客户端 - 用自然语言和你的数据对话
数据库·mongodb·nosql·agent·桌面客户端
团象科技2 小时前
从一线实操案例拆解不同出海团队落地海外VPS运维独立站的路径细节
大数据·数据库·人工智能