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

相关推荐
李广坤11 小时前
MySQL 大表字段变更实践(改名 + 改类型 + 改长度)
数据库
Turnip12022 天前
深度解析:为什么简单的数据库"写操作"会在 MySQL 中卡住?
后端·mysql
爱可生开源社区2 天前
2026 年,优秀的 DBA 需要具备哪些素质?
数据库·人工智能·dba
随逸1772 天前
《从零搭建NestJS项目》
数据库·typescript
加号32 天前
windows系统下mysql多源数据库同步部署
数据库·windows·mysql
シ風箏2 天前
MySQL【部署 04】Docker部署 MySQL8.0.32 版本(网盘镜像及启动命令分享)
数据库·mysql·docker
李慕婉学姐2 天前
Springboot智慧社区系统设计与开发6n99s526(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
百锦再2 天前
Django实现接口token检测的实现方案
数据库·python·django·sqlite·flask·fastapi·pip
WeiXin_DZbishe2 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
tryCbest2 天前
数据库SQL学习
数据库·sql