exist和in的区别?
数据库 MySQL
官方 推荐
-- in
select * from a where id in (select id from b);
-- exists
select * from A where exists(select 1 from B where B.id = A.id);


使用in时,sql语句是先执行子查询,也就是先查询子表b,再查主表a。而使用exists是先查主表a ,再查询子表b。


根据小表驱动大表(即小的数据集驱动大的数据集)的原则,如果主查询中的表较大且又有索引时应该用in。 反之如果外层的主查询记录较少,子查询中的表大,又有索引时使用exists。


还有一点注意的是用 exists 该子查询实际上并不返回任何数据,而是返回值True或False。


not in 和not exists

如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists都比not in要快。