当前位置: 首页 > news >正文

MySQL联合索引、索引下推Demo

 1.联合索引

测试SQL语句如下:表test中共有4个字段(id, a, b, c),id为主键

drop table test;#建表
create table test(id bigint primary key auto_increment,a int,b int,c int
)#表中插入数据
insert into test(a, b, c) values(1,2,3),(2,3,4),(4,5,6);
insert into test(a, b, c) values(1,2,3),(2,3,4),(4,5,6);
insert into test(a, b, c) values(1,2,3),(2,3,4),(4,5,6);# 建立联合索引(a,b,c)
create index index_abc ON test (a, b, c);# 删除索引
drop index index_abc on test;# 查询a = 1 and c = 3,观察这条语句是否走了索引
explain 
select a,b,c from test where a = 1 and c = 3; # 存在回表的可能explain 
select a,b,c from test where a = 1; # 完全使用索引

首先不建立联合索引(a,b,c),执行下面的执行

explain 
select a from test where a = 1 and c = 3; # 存在回表的可能

结果下如下: 使用主键的覆盖索引查询,没有走索引

建立联合索引(a,b,c)后,同样执行上面语句,结果如下:

通过explain,我们发现,这条语句可以走索引,同时还存在Using where,说明存在回表的可能,但是这条语句是可以走索引的。(部分索引)

如果我们执行下面这条语句:(符合最左前缀原则

explain 
select a,b,c from test where a = 1; # 完全使用索引

 结果如下:说明完全使用索引来查询。

 2.索引下推ICP

ICP可以减少存储引擎必须访问基本表的次数以及服务器必须访问存储引擎的次数,这是是否使用ICP的最可靠的判断条件

SQL语句如下:

create table test01(`id` bigint primary key auto_increment,`name` varchar(64),`age` int,`desc` varchar(64)
)# 插入测试数据
insert into test01(name, age) values('张三1', 18);
insert into test01(name, age) values('张三2', 21);
insert into test01(name, age) values('张三3', 22);
insert into test01(name, age) values('李四', 18);
insert into test01(name, age) values('王五', 13);# 为name和age建立联合索引
create index index_na on test01(name, age);# 观察name like '张%' and age = 18
explain
select * from test01 where `name` like '张%' and `age` = 18;explain
select name, age from test01 where `name` like '张%' and `age` = 18;

首先给name和age建立联合索引

然后执行下面这条语句

explain
select * from test01 where `name` like '张%' and `age` = 18;

结果如下:

Using index condition说明使用了索引下推,并且存在回表的现象,因为select *

http://www.lryc.cn/news/458167.html

相关文章:

  • linux上复制命令cp的常见用法-ubuntu
  • R语言绘制气泡图
  • c++ sparsetable 模版
  • 创建线程池和封装锁
  • 易图讯军用VR三维电子沙盘系统
  • LeetCode讲解篇之70. 爬楼梯
  • 论文写作不再难,论文初稿快速成型法!
  • linux系统,监控进程运行状态并自动重启崩溃后的进程的多种方法
  • 【JavaEE初阶】深入理解不同锁的意义,synchronized的加锁过程理解以及CAS的原子性实现(面试经典题);
  • 详解Redis分布式锁在SpringBoot的@Async方法中没锁住的坑
  • 怎么做接口自动化测试
  • 网络编程(18)——使用asio协程实现并发服务器
  • Koa2项目实战2(路由管理、项目结构优化)
  • 决战Linux操作系统
  • OceanBase 3.2.2 数据库问题处理记录
  • HCIP--以太网交换安全(二)端口安全
  • 在 Windows 11 安卓子系统中安装 APK 的操作指南
  • [C语言] 函数详解:库函数与自定义函数
  • 0x11 科迈 RAS系统 Cookie验证越权漏洞
  • MoonBit 双周报 Vol.57:AI助手功能增强、表达式优先级调整、JS 交互优化、标准库与实验库API多项更新!
  • element ui input textarea控制显示高度
  • Chromium 中chrome.downloads扩展接口c++
  • 微信小程序常见问题
  • 进程的理解
  • LeetCode494:目标和
  • vue3中自定义校验函数密码不生效问题
  • RabbitMQ(死信队列)
  • HTTP代理的优点和局限性
  • 大厂面试真题-如果通过JVM自带的工具排查和解决线上CPU100%的问题
  • kubernetes中微服务部署