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 小时前
怎么给字符串字段加索引?日志系统 一条更新语句是怎么执行的
java·数据库·sql·mysql·引擎
大厂技术总监下海12 小时前
数据湖加速、实时数仓、统一查询层:Apache Doris 如何成为现代数据架构的“高性能中枢”?
大数据·数据库·算法·apache
LeenixP12 小时前
RK3576-Debian12删除userdata分区
linux·运维·服务器·数据库·debian·开发板
知行合一。。。12 小时前
Python--03--函数入门
android·数据库·python
哈里谢顿12 小时前
小探mysql覆盖索引
mysql
X***078812 小时前
理解 MySQL 的索引设计逻辑:从数据结构到实际查询性能的系统分析
数据库·mysql·sqlite
爬山算法12 小时前
Hibernate(31)Hibernate的原生SQL查询是什么?
数据库·sql·hibernate
warton8812 小时前
ubuntu24 安装 proxsql 实现数据库代理
linux·运维·mysql·ubuntu
Yuiiii__12 小时前
一次并不简单的 Spring 循环依赖排查
java·开发语言·数据库
-曾牛12 小时前
Yak语言核心基础:语句、变量与表达式详解
数据库·python·网络安全·golang·渗透测试·安全开发·yak