如何将SQL中通过第三个表关联的两个表相关联?

时间:2014-01-23 19:05:16

标签: sql sql-server tsql join relational

我的SQL技能已经萎缩,我需要一些帮助将两个表连接到第三个表,其中包含对这两个表的外键。

Customer表包含我需要的数据。地址表包含我需要的数据。它们彼此不直接相关,但CustomerAddress表同时具有CustomerID和AddressID列。

具体来说,我需要来自Customer表:

FirstName
MiddleName
LastName

...来自地址表:

AddressLine1
AddressLine2
City
StateProvince, 
CountryRegion
PostalCode

这是我的尴尬尝试,LINQPad甚至无法识别的语法(“'='附近的语法不正确”)。

select C.FirstName, C.MiddleName, C.LastName, A.AddressLine1, A.AddressLine2, A.City, A.StateProvince, 
A.CountryRegion, A.PostalCode
from SalesLT.Customer C, SalesLT.Address A, SalesLT.CustomerAddress U
left join U.CustomerID = C.CustomerID
where A.AddressID = U.AddressID

注意:这是一个SQL Server表,特别是AdventureWorksLT2012_Data.mdf

3 个答案:

答案 0 :(得分:3)

select C.FirstName, C.MiddleName, C.LastName, A.AddressLine1, A.AddressLine2, A.City, A.StateProvince, 
A.CountryRegion, A.PostalCode
from  SalesLT.CustomerAddress U INNER JOIN SalesLT.Address A
ON A.AddressID = U.AddressID
INNER JOIN  SalesLT.Customer C
ON U.CustomerID = C.CustomerID  

我只使用了INNER JOINS但显然您可以根据您的要求将其替换为LEFTRIGHT联接。

答案 1 :(得分:3)

SELECT
    c.FirstName,
    c.MiddleName,
    c.LastName,
    a.AddressLine1
    a.AddressLine2
    a.City
    a.StateProvince, 
    a.CountryRegion
    a.PostalCode
FROM Address a
JOIN CustomerAddress ca
    ON ca.AddressID = a.AddressID
JOIN Customer c
    ON c.CustomerID = ca.CustomerID
WHERE ...

答案 2 :(得分:1)

LEFT JOIN将包括没有地址的客户。

    SELECT C.FirstName, C.MiddleName, C.LastName, A.AddressLine1, 
    A.AddressLine2, A.City, A.StateProvince, 
    A.CountryRegion, A.PostalCode
    FROM  Customer C
    LEFT JOIN CustomerAddress U 
    ON U.CustomerID = C.CustomerID  
    LEFT JOIN Address A
    ON A.AddressID = U.AddressID
    ORDER BY C.LastName, C.FirstName