gpt4 book ai didi

sql - 奇怪的 INNER JOIN 语法和封装

转载 作者:行者123 更新时间:2023-12-02 19:30:11 24 4
gpt4 key购买 nike

我通常非常熟悉 JOINS,但这是新的。

假设三个表(两个表和第三个链接器表的经典情况):

Customer  Product  Transaction--------  -------  -----------ID        ID       CustomerIDName      Desc     ProductID          Cost     Date

(Simplistic on purpose, I can't reproduce the actual structure, it's not my code.)

Normally, to get a table of "who bought what when", I'd do this:

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

但我已经看到了这个:

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

这是什么?只是另一种语法,还是性能技巧?

(它是在 SQLServer 上,仅供引用,但大概可以应用于其他...)

最佳答案

括号不会改变语义。 ON 子句的位置控制连接逻辑处理的顺序。

第一个查询

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

第二个查询

(删除多余的括号)

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, Customer 的联接,然后将由此产生的虚拟表联接到 Product

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

这是covered by Itzik Ben Gan here但该文章有许多不准确之处,请参阅follow up letter by Lubor Kollar也是如此。

关于sql - 奇怪的 INNER JOIN 语法和封装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8068301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com