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

相关推荐
Yushan Bai15 小时前
ORACLE Enterprise Manager Cloud Control 系列测试2- 日常管理和SQL优化
数据库·oracle
-To be number.wan15 小时前
数据库单表查询全攻略
数据库·学习
文心快码BaiduComate15 小时前
520,Comate Mission模式跨越界限,和你达成最「深」联动
前端·数据库·后端
杨云龙UP16 小时前
Oracle RAC/ODA环境下如何准确查询PDB表空间已分配大小?一次说清Oracle表空间逻辑大小和ASM三副本实际占用_2026-05-19
linux·运维·数据库·sql·oracle·ffmpeg
@nengdoudou16 小时前
KingbaseES数据库MySQL模式使用 “GROUP BY“
数据库·mysql
晨曦中的暮雨16 小时前
3.20字节云部门一面|面经
数据库·oracle
万邦科技Lafite16 小时前
实战演练:利用京东API一键抓取商品详情
数据库·redis·python·缓存·开放api·淘宝开放平台
LIUAWEIO16 小时前
接口 data 满屏反斜杠,怎么展开?
java·开发语言·数据库·json在线解析·data是字符串·json转义·二次json
沪漂阿龙17 小时前
面试题详解:大模型设计沙箱全攻略——LLM Sandbox、Agent 工具执行、代码沙箱、安全隔离、权限控制与工程落地
网络·数据库·人工智能·安全
IT策士17 小时前
Django 从 0 到 1 打造完整电商平台:Admin 后台管理与数据初始化
数据库·django·sqlite