0
点赞
收藏
分享

微信扫一扫

in,not in,exists,not exists使用方法和区别

自信的姐姐 2022-03-30 阅读 69
select a.* from A a where exists(select 1 from B b where a.id=b.id);

select a.* from A a where not exists(select 1 from B b where a.id=b.id);

select * from A where id in(select id from B);

select * from A where id not in(select id from B);

对于以上两种查询条件,in是把外表和内表作hash 连接,而exists 是对外表作loop 循环,每次loop 循环再对内表进行查询。

in()适合B表数据量小于A表数据量的情况
exists()适合B表数据量大于A表数据量情况
当A表数据与B表数据一样大时,in与exists效率差不多,可任选一个使用

exists,not exists后跟的是一个true或者是false

in和exists区别
in在查询的时候,确定给定的值是否与子查询或列表中的值相匹配。首先查询子查询的表,然后将从表和主表做一个笛卡尔积,然后按照条件进行筛选。所以相对从表比较小的时候,in的速度较快。
exists是指定一个子查询,检测行的存在。遍历循环外表,然后看外表中的记录有没有和内表的数据一样的。匹配上就将结果放入结果集中。

举报

相关推荐

0 条评论