sql - 使用和不使用连接的查询性能

标签 sql sql-server database

假设我们有两个表

客户订单

客户表:-

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/

相关文章:

c# - 使用 Entity Framework 从 SQL 数据库中获取除 SQL 之外的所有内容

sql-server - sql server 中的 CASE - 实现澄清?

sql-server - SSRS 2008 : Passing Parameters to linked report

ios - 核心数据与服务器数据同步

MySQL : InnoDB_Force_recovery = 1 leads to table in read only

SQL 和 DB2 创建命令

sql - Oracle 对 View 使用提示索引并强制其到基表

sql - 如何从 Sproc 中识别存储过程的调用者

mysql - SQL 计数、求和和分组依据

sql - Postgresql 更新插入查询