MySQL - exists和in, not exists和not in

【1】exists

对外表用loop逐条查询,每次查询都会查看exists的条件语句。

当 exists里的条件语句能够返回记录行时(无论记录行是多少,只要能返回),条件就为真 , 返回当前loop到的这条记录。反之如果exists里的条件语句不能返回记录行,条件为假,则当前loop到的这条记录被丢弃。

exists的条件就像一个boolean条件,当能返回结果集则为1,不能返回结果集则为 0。

语法格式如下:

select * from tables_name where [not] exists(select..);
  •  

示例如下:

select * from p_user_2 
where  EXISTS(select * from p_user where id=12)
  •  

如果p_user表中有id为12的记录,那么将返回所有p_user_2表中的记录;否则,返回记录为空。

如果是not exists,则与上述相反。

总的来说,如果A表有n条记录,那么exists查询就是将这n条记录逐条取出,然后判断n遍exists条件


【2】in

语法格式如下:

select * from A where column in (select column from B);
  •  

需要说明的是,where中,column为A的某一列,in 所对应的子查询语句返回为一列多行结果集。

注意,in所对应的select语句返回的结果一定是一列!可以为多行。

示例如下:

select * from p_user_2 where id [not] in (select id from p_user )
  •  

查询id在p_user表id集合的p_user_2的记录。not in则相反。


【3】exists与in的关系

经过sql改变,二者是可以达到同一个目标的:

select * from p_user_2 
where id [not] in (select id from p_user );

select * from p_user_2 
where [not] EXISTS (select id from p_user where id = p_user_2.id )

那么什么时候用exists 或者in呢?

如果查询的两个表大小相当,那么用in和exists差别不大。

如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in

例如:表A(小表),表B(大表)

① 子查询表为表B:

select * from A 
where cc in (select cc from B) 
//效率低,用到了A表上cc列的索引;

select * from A 
where exists(select cc from B where cc=A.cc) 
//效率高,用到了B表上cc列的索引。 

② 子查询表为表A:

select * from B 
where cc in (select cc from A) 
//效率高,用到了B表上cc列的索引;

select * from B 
where exists(select cc from A where cc=B.cc) 
//效率低,用到了A表上cc列的索引。

not in 和not exists如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。

所以无论哪个表大,用not exists都比not in要快

 

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值