这个题不难,找到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);