exists 和 in 的区别

这是个很很很基础的知识,但是自己总是会忘,故记下来,免得每次百度。。。

话不多说,看代码

  • IN:
select * from student 
    where student_id in (
      select student_id from subject 
    )

in 执行流程:
1.首先执行子查询:
select student_id from subject
2.将1中的查询结果与student表做笛卡尔积
3.去除student.student_id与subject.student_id 不相等的行。最后就得到数据了。

从上述流程我们很容易得出结论:用in时,我们内表数据量应该小

  • EXISTS
    select … from …exists(….)

注:exists的返回结果是bool型,只有true或者false,要么全查要么不查

select * from student 
    where  exists(
       select student_id from subject  
       where student.student_id = subject.student_id
    )

以上sql的查询结果与用in的查询结果一致。
exists 的执行流程:
1.查询主查询的表

select * from student 

2.根据1中查询的结果来判断where后的条件是否成立。

exists(
       select student_id from subject  
       where student.student_id = subject.student_id
    )

由上述流程我们又可以很容易的得出,用exists时,外表要小些比较好。

拓展:not in 和not exists

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

总结,sql查询万变不离其宗,先查小表,判读条件尽量去除多的数据。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值