【问题标题】:SQL many-to-many JOINSQL 多对多 JOIN
【发布时间】:2015-11-24 12:09:43
【问题描述】:

我在连接两个表时遇到了困难。

我有桌子

Customer_table
 ---------------------------------------
| CustomerId(PK) | Firstname | Lastname |
 ---------------------------------------

CustomerInterest_table
 ----------------------------------------
| CustomerId(PK,FK) | InterestId(PK,FK)  |
 ----------------------------------------

Interest_table
 -------------------------------
| InterestId(PK) | InterestInfo |
 -------------------------------

我要做的是选择每个客户,并将兴趣与桌上的 FK 参考加入。

最终我想获取一个结果,其中包含从客户表中获取的客户,以及从 CustomerInterest_table 中获取的客户兴趣。

我喜欢构建这样的对象

{
customerId : 'Id12345,
firstname : 'John', 
lastname : 'Doe', 
interests : [{interestId : 1, interestInfo : 'Apples'}]
}

我将如何获取和加入表格? 非常感谢任何帮助。

【问题讨论】:

    标签: sql sql-server join many-to-many


    【解决方案1】:

    数据库设计(First Normal Form)假设该列应该是简单类型,在您的情况下它意味着没有数组。相反,您可以从多个选定的行中获取所需的数据:

    SELECT customerId, firstname, lastname, interestId, InterestInfo 
        FROM Customer_table c
        INNER JOIN CustomerInterest_table tc
            ON c.customerId = tc.customerId
        INNER JOIN Interest_table i 
            ON tc.InterestId = i.InterestId
    ORDER BY customerId
    

    最后一个ORDER BY 允许您强制对行进行排序,这样同一客户的兴趣就会一个接一个地跟随。

    或者,如果客户可能没有兴趣,您可以利用 LEFT JOIN(然后两列interestId,InterestInfo 将为 NULL)

    SELECT customerId, firstname, lastname, interestId, InterestInfo 
        FROM Customer_table c
        LEFT OUTER JOIN CustomerInterest_table tc
            ON c.customerId = tc.customerId
        INNER JOIN Interest_table i 
            ON tc.InterestId = i.InterestId
    ORDER BY customerId
    

    更新

    或者(如果您真的想要单列中的所有内容不惜任何代价)您可以将结果转换为 XML 数据类型,然后最后一列将组成复杂的 XML:

    SELECT customerId, firstname, lastname
     , [Name]
     , (STUFF((SELECT CAST(', ' + interestId AS VARCHAR(MAX) + ':' + InterestInfo) 
         FROM Interest_table i
         WHERE tc.InterestId = i.InterestId
         FOR XML PATH ('')), 1, 2, '')) AS interests 
    FROM Customer_table c
        INNER JOIN CustomerInterest_table tc
            ON c.customerId = tc.customerId
    

    (p.s. 抱歉语法没有检查正确性)

    【讨论】:

    • 你打败了我,除了 Order By 子句。没想到:)
    • 谢谢!很棒的方法,并且 +1 用于处理零利益!像魅力一样工作,
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2021-03-27
    • 2011-03-03
    相关资源
    最近更新 更多