1

我正在使用 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;
4

2 回答 2

2

这是因为WHERE查询1中的子句。该WHERE子句过滤了被连接的两个表的最终结果。您需要将条件 fromWHERE子句移至ON它首先过滤记录(在表上Sales.SalesOrderHeader),然后再将其加入另一个表(Sales.Customer您也可以在此处找到它。

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';
于 2013-09-23T17:31:32.100 回答
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';
于 2013-09-23T17:32:32.680 回答