SQL中的not in 与 not exists

一. inexists
in是把外表和内表作hash连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询 。

select * from TABLE1 a where a.id in (select b.id from TABLE2 b);  --用到了TABLE1表上id列的索引,而子查询里的表的索引没用到;
select * from TABLE1 a where exists (select b.id from TABLE2 where b.id=a.id);  -- 用到了子查询里的表TABLE2表上id列的索引。
-- 备注:TABLE1与TABLE2两个表大小相当,用in和exists差别不大;如果两个表中一个较小一个较大,则子查询表大的用exists,子查询表小的用in;速度较快。

二. not innot exists

SELECT * FROM TABLE1 a WHERE a.id NOT IN (SELECT b.id FROM TABLE2 b);
SELECT * FROM TABLE1 a WHERE  NOT EXISTS (SELECT b.id FROM TABLE2 b WHERE a.ID = b.ID);

not in(会调用子查询), not exists(会调用关联子查询)

  • 如果子查询中返回的任意一条记录含有空值,使用 not in 则查询将不返回任何记录;
  • 如果子查询字段有非空限制,则可以使用not in
  • 如果查询语句使用了not in,那么对内外表都进行全表扫描,没有用到索引;而用not exists的子查询依然能用到表上的索引。

备注: 如果子查询结果有任意一套记录含有null,使用 not in 查询不出来结果

本文地址:https://blog.csdn.net/hyfstyle/article/details/110544006

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐