假设我们有两个表
客户和订单
客户表:-
custid custname
------- ---------
1 aaa
2 bbb
3 ccc
订单表:-
orderid custid date
-------- ------ -----
101 1 2016-03-01
102 1 2016-03-03
103 2 2016-03-01
现在,我们已经展示了没有下订单的客户
我们可以通过几种方式做到这一点:-
1.不加入
Select custid
from Customers
where custid not in
(Select custid from Orders)
和
2.加入
Select C.custid
from Customers C left join Orders O
on C.custid = O.custid
where O.orderid is null
有人问我会有任何性能差异吗?如果有,哪个会做得更好,为什么?
最佳答案
两个查询不同,所以比较无效..查询相同/获得相同的执行计划..
1.将第一个查询中的 Not IN
替换为 Not Exists
*
如果你这样做,你可能会得到相同的查询计划和相同的处理...
*为什么 Not IN
被要求删除,除了当涉及空值时它可能给你奇怪的结果的原因外,可以从这个答案中找到 Not IN vs Not Exists
粘贴答案中的相关术语..
The execution plans may be the same at the moment but if either column is altered in the future to allow NULLs the NOT IN version will need to do more work (even if no NULLs are actually present in the data) and the semantics of NOT IN if NULLs are present are unlikely to be the ones you want anyway.
关于sql - 使用和不使用连接的查询性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39036901/