且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

奇怪的INNER JOIN语法和封装

更新时间:2022-12-06 18:54:42

括号不会更改语义. ON子句的位置控制联接的逻辑处理顺序.

The parentheses do not change the semantics. The position of the ON clause controls the order of the logical processing of joins.

SELECT Customer.Name,
       Product.Desc,
       Transaction.Date
FROM   Product
       INNER JOIN Transaction
         ON Transaction.ProductID = Product.ID
       INNER JOIN Customer
         ON Transaction.CustomerID = Customer.ID 

第二个查询

(已删除多余的括号)

Second Query

(Redundant parentheses removed)

SELECT Customer.Name,
       Product.Desc,
       Transaction.Date
FROM   Product
       INNER JOIN Transaction
                  INNER JOIN Customer
                    ON Transaction.CustomerID = Customer.ID
         ON Transaction.ProductID = Product.ID 

因此,在第一个示例中逻辑上,首先发生Transaction, Product上的联接,然后将由此产生的虚拟表联接到Customer上,而在第二个示例中,发生Transaction, Customer上的联接首先,然后将由此产生的虚拟表连接到Product

So logically in your first example the join on Transaction, Product happens first then the virtual table resulting from that is joined onto Customer, whereas in your second example the join on Transaction, Customer happens first then the virtual table resulting from that is joined on to Product

这仅是逻辑上的,并且由于内部联接既具有关联性又具有可交换性,因此这可能不会对执行计划产生任何影响(除非您向查询中添加OPTION (FORCE ORDER)),但是它可以用于外部联接.

This is only logically and as inner joins are both associative and commutative this likely won't make any difference to the execution plan (unless you add OPTION (FORCE ORDER) to the query) but it can do for outer joins.

这是Itzik Ben Gan在这里发现的,但是文章有许多错误之处,请参见 Lubor Kollar的跟进信也是

This is covered by Itzik Ben Gan here but the article has a number of inaccuracies, see the follow up letter by Lubor Kollar as well.