【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:

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章