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

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

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

会发现俩次的数据是一致的,所以下来我们来说一下,在那些情况用in 那些情况用exists
select * from book b where bookid in (select id from class);它的运行方式是这样的,类似于俩个for循环for select * from classfor select * from book where book.id=class.idselect * from book b where exists (select 1 from class where b.bookid=id );exists的运行方式如下for select * from bookfor select * from class where class.id=book.id
以上俩个案例简单来说 :
如果查询的两个表大小相当,那么用in和exists差别不大。
如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in:

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号