【问题标题】:How can I relate two tables in SQL that are related through a third one?如何在 SQL 中关联通过第三个关联的两个表?
【发布时间】:2014-02-14 12:45:49
【问题描述】:

我的 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

【问题讨论】:

    标签: sql sql-server tsql join relational


    【解决方案1】:
    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 连接。

    【讨论】:

    • 把它想象成一个链条。从一个作为“主”的表开始,然后开始一次连接一个表。
    【解决方案2】:
    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 ...
    

    【讨论】:

      【解决方案3】:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-27
        相关资源
        最近更新 更多