为什么这两个查询返回不同的行数

时间:2013-09-23 17:28:56

标签: tsql

我正在使用adventureworks2012:

第一个查询返回43行并且没有空值,而第二个返回超过19,000个并且返回大量空值。

我认为外部联接返回了查询左侧的行,即使条件不满足,因此两个查询应该是等价的?

- 1

SELECT c.CustomerID, s.SalesOrderID, s.OrderDate
FROM Sales.Customer AS c
LEFT OUTER JOIN Sales.SalesOrderHeader AS s ON c.CustomerID = s.CustomerID
WHERE s.OrderDate = '2005/07/01';

- 2

WITH orders AS (
SELECT SalesOrderID, CustomerID, OrderDate
FROM Sales.SalesOrderHeader
WHERE OrderDate = '2005/07/01'
)
SELECT c.CustomerID, orders.SalesOrderID, orders.OrderDate
FROM Sales.Customer AS c
LEFT OUTER JOIN orders ON c.CustomerID = orders.CustomerID
ORDER BY orders.OrderDate DESC;

2 个答案:

答案 0 :(得分:2)

这是因为查询1中的WHERE子句。WHERE子句过滤了要连接的两个表的最终结果。您需要将条件从WHERE子句移动到ON首先过滤记录(在表Sales.SalesOrderHeader上),然后再将其连接到另一个表(Sales.Customeryou can also find it here.

SELECT c.CustomerID, s.SalesOrderID, s.OrderDate
FROM   Sales.Customer AS c
       LEFT OUTER JOIN Sales.SalesOrderHeader AS s 
           ON c.CustomerID = s.CustomerID  AND 
              s.OrderDate = '2005/07/01';

答案 1 :(得分:2)

您通过引用位于其中的表来杀死第一个外部 只需将该条件移入连接

即可
SELECT c.CustomerID, s.SalesOrderID, s.OrderDate
 FROM Sales.Customer AS c
 LEFT OUTER JOIN Sales.SalesOrderHeader AS s 
   ON c.CustomerID = s.CustomerID
  AND s.OrderDate = '2005/07/01';