将条件放入 JOIN 子句与 WHERE 子句之间是否有任何区别(性能、最佳实践等)?
例如…
-- Condition in JOIN SELECT * FROM dbo.Customers AS CUS INNER JOIN dbo.Orders AS ORD ON CUS.CustomerID = ORD.CustomerID AND CUS.FirstName = 'John' -- Condition in WHERE SELECT * FROM dbo.Customers AS CUS INNER JOIN dbo.Orders AS ORD ON CUS.CustomerID = ORD.CustomerID WHERE CUS.FirstName = 'John'
你更喜欢哪个(也许是为什么)?
关系代数允许WHERE子句和中的谓词可互换INNER JOIN,因此即使是INNER JOIN带有子句的查询也可以让优化器重新排列谓词,以便在处理过程WHERE中它们 可能已经被排除在外JOIN。
WHERE
INNER JOIN
JOIN
我建议您以最易读的方式编写查询。
有时这包括制作INNER JOIN相对“不完整”的标准并将一些标准WHERE简单地放入其中以使过滤标准列表更易于维护。
例如,而不是:
SELECT * FROM Customers c INNER JOIN CustomerAccounts ca ON ca.CustomerID = c.CustomerID AND c.State = 'NY' INNER JOIN Accounts a ON ca.AccountID = a.AccountID AND a.Status = 1
写:
SELECT * FROM Customers c INNER JOIN CustomerAccounts ca ON ca.CustomerID = c.CustomerID INNER JOIN Accounts a ON ca.AccountID = a.AccountID WHERE c.State = 'NY' AND a.Status = 1
但这当然取决于。