exist和in的区别:
select * from a where id in(select id from b);
select * from a where id exists(select id from b);
(1)使用in,sql会先执行子查询;即先查询b表,在查a表;
对于主表数据较多时,我们使用in速度比exist更快。即优先查询数据较少的子表b。
(2)使用exists,sql会先进行主表查询,再进行子查询;
子表b较大时,使用exist插叙速度更快(都会使用索引)。即优先查询较小的主表a。
(3)如果使用的是not in与not exists,直接使用not exists,因为not in 会进行全表扫描,不走索引,not exists会走索引。
总结:使用in和exist的重点在于优先查询数据较小的表,再进行较大表的查询。
in优先查询后面的,exist优先查询前面的。