【MySQL优化】in 和 exists 使用区别

点击查看MySQL优化系列文章集锦,从头到尾全部案例均配备源码,让你轻松看文章,轻松实践
如你不想自己测试案例,可直接看优化总结,了解知识点即可

本篇文章没有实际案例,只说明用法

  • 首先我们先来看俩张表
  • book
  • class

在这里插入图片描述

这个时候我们使用in来进行一次查询 bookid存在class表的数据

select * from book b where bookid in (select id from class);

在这里插入图片描述

然后使用exists来进行一次查询 bookid存在class表的数据

select * from book b where exists (select 1 from class where b.bookid=id );

在这里插入图片描述
会发现俩次的数据是一致的,所以下来我们来说一下,在那些情况用in 那些情况用exists

使用场景

  • 当book表的数据集小于class的数据集时 用in 优于exists
  • 当class表的数据集小于book的数据集时 用exists 优于in
select * from book b where bookid in (select id from class);
它的运行方式是这样的,类似于俩个for循环
for select * from class
for select * from book where book.id=class.id

select * from book b where exists (select 1 from class where b.bookid=id );
exists的运行方式如下
for select * from book
for select * from class where class.id=book.id

以上俩个案例简单来说 :

  • 如果查询的两个表大小相当,那么用in和exists差别不大。

  • 如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

咔咔-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值