联接三个或更多表

虽然每个联接规范只联接两个表,但 FROM 子句可包含多个联接规范。这样一个查询可以联接许多表。

AdventureWorks 数据库的 ProductVendor 表是一个很好的示例,在该示例联接两个以上的表非常有用。下面的 Transact-SQL 查询将查找特定子类别的所有产品的名称和产品供应商的名称:

SELECT p.Name, v.Name
FROM Production.Product p
JOIN Purchasing.ProductVendor pv
ON p.ProductID = pv.ProductID
JOIN Purchasing.Vendor v
ON pv.VendorID = v.VendorID
WHERE ProductSubcategoryID = 15
ORDER BY v.Name

下面是结果集。

Name                                               Name
LL Mountain Seat/Saddle                            Chicago City Saddles
ML Mountain Seat/Saddle                            Chicago City Saddles
HL Mountain Seat/Saddle                            Chicago City Saddles
LL Road Seat/Saddle                                Chicago City Saddles
ML Road Seat/Saddle                                Chicago City Saddles
HL Road Seat/Saddle                                Chicago City Saddles
LL Touring Seat/Saddle                             Chicago City Saddles
ML Touring Seat/Saddle                             Chicago City Saddles
HL Touring Seat/Saddle                             Chicago City Saddles
HL Touring Seat/Saddle                             Expert Bike Co
ML Touring Seat/Saddle                             Expert Bike Co
LL Touring Seat/Saddle                             Expert Bike Co
HL Road Seat/Saddle                                First Rate Bicycles
LL Mountain Seat/Saddle                            First Rate Bicycles
ML Mountain Seat/Saddle                            First Rate Bicycles
LL Road Seat/Saddle                                Hill's Bicycle Service
ML Road Seat/Saddle                                Hill's Bicycle Service
HL Mountain Seat/Saddle                            Hybrid Bicycle Center

(18 row(s) affected)

请注意,FROM 子句中的一个表 ProductVendor 不会向结果提供任何列。而且,联接列 ProductID 和 VendorID 都不会出现在结果中。尽管如此,只有将 ProductVendor 用作中间表,此联接才有可能实现。

由于 ProductVendor 表是参与联接的其他表之间的中间连接点,因此联接的中间表(ProductVendor 表)可称为“转换表”或“中间表”。

如果同一语句中包含多个联接运算符,无论是用于联接两个以上的表还是用于联接两个以上的列对,联接表达式都可以通过 AND 或 OR 连接在一起。