mysql in exists

c8e0de624e464fe7adaea2162a0756a3.png

a0442cc4c0674fc18673afff20432d18.png 

 

这个题不难,找到red的销售人员,排除掉就可以了。
学习和比较,比解题更有趣。
not in和not exists和left join。
平常工作开发中,他们之间的效率比较大多是left join > not exists > not in
但是这次就不一样,left join > not in > not exists
主要看这个not in 和 not exists。
为什么呢?因为子表的查询语句比较复杂,而结果集非常简单,只有两个结果。
not in 只会查询一次,便把结果集缓存到内存中,而not exists则是每次都会查询。因此,耗时要比not in 多许多。
例:
select * from A where A.userId in (select id from B where id > 100);
select * from A where exist (select id from B where id > 100 and A.userId = B.id);

exists是A.length次查询,和B表数量关系不大。而in的话,B表查询出来的结果集越大,每次遍历就越耗时。

如果是括号内查询语句耗时,且查询结果集数量小时,用in合适,如果查询语句简单并且查询结果集大时,用exist合适。

代码

 

 

-- not in

select name from SalesPerson s where s.sales_id not in (SELECT o.sales_id from company c inner join Orders o on c.com_id = o.com_id and c.name = 'RED');

-- not exists
select name from SalesPerson s where not exists (SELECT o.sales_id from company c inner join Orders o on c.com_id = o.com_id and c.name = 'RED' where s.sales_id = o.sales_id);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值