【问题标题】:Create multiple joins to a lookup table from one table从一个表创建到查找表的多个连接
【发布时间】:2020-03-27 01:10:36
【问题描述】:

假设我在 sql 中有一个表 A,数据如下所示

现在我有另一个查找表 Table B

现在我如何从查找表 B 中获取同一记录的类型名称和公司名称的值。 例如,对于类型为 T1 的记录,对于同一记录 Request_ID = 1,它应返回类型名称为“产品”和业务名称为“SCI”。我使用内连接来执行此操作,但由于表 A 中的相同记录它会发生冲突尝试从查找表中获取相应的值。

Select B.name, A.type,A.business_line 
from Table A A 
inner join Table B B on A.request_id = B.id

【问题讨论】:

  • 我们无法使用数据作为图像。请以表格格式text 或(更好)为 DDL 和 DML 语句提供您的数据。您还需要向我们展示您期望的结果。帮助我们帮助您。

标签: sql join sql-server-2012


【解决方案1】:

你需要JOIN表A到表B两次,一次得到Type Name,一次得到Business Name

SELECT a.request_id, a.type, b1.name AS [Type Name], a.business_line, b2.name AS [Business Name]
FROM TableA a
JOIN TableB b1 ON b1.code = a.type
JOIN TableB b2 ON b2.code = a.business_line

Demo on dbfiddle

【讨论】:

    【解决方案2】:

    您只需使用单独的连接引用查找表两次,即可检索 2 个值。下面的示例向您展示了如何做到这一点,并且链接上有一个可运行的演示:

    -- setup demo schema with data
    create table TableA 
    (
      request_id int,
      [type] nvarchar(10),
      [business_line] nvarchar(10)  
    );
    
    create table TableB 
    (
      id int,
      [code]  nvarchar(10),
      [name]  nvarchar(10)
    );
    
    INSERT INTO TableA
        ([request_id], [type], [business_line])
    VALUES
        (1, 'T1', 'BL1'),
        (2, 'T1', 'BL2'),
        (3, 'T2', 'BL3'),
        (4, 'T1', 'BL1')
    ;
    
    INSERT INTO TableB
        (id, [code], [name])
    VALUES
        (19, 'BL1', 'SCI'),
        (20, 'BL2', 'PCI'),
        (67, 'T1', 'Product'),
        (68, 'T2', 'Substance')
    ;
    

    查询

    select A.request_id, A.[type], A.[business_line], 
            Btype.[name] as Type_Name, 
            BName.[name] as Business_Name
    from TableA A
    inner join TableB BType on A.[type] = BType.[code]
    inner join TableB BName on A.[business_line] = BName.[code];
    

    产生:(注意第 3 行在您的示例数据中没有匹配的查找

    | request_id | type | business_line | Type_Name | Business_Name |
    | ---------- | ---- | ------------- | --------- | ------------- |
    | 1          | T1   | BL1           | Product   | SCI           |
    | 2          | T1   | BL2           | Product   | PCI           |
    | 4          | T1   | BL1           | Product   | SCI           |
    

    如果您的行没有查找值,您可以修改查询连接,这样就不会像第 3 行那样排除行。

    View on DB Fiddle

    【讨论】:

      【解决方案3】:

      你只想要两个joins 吗?

      select r.name as producct, l.name as businessname,
             a.type, a.business_line
      from a join
           lookup r
           on a.request_id = r.id join
           lookup l
           on a.business_line = l.id;
      

      【讨论】:

        猜你喜欢
        • 2018-05-16
        • 2014-05-29
        • 2015-10-17
        • 1970-01-01
        • 2011-05-07
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 2012-06-17
        相关资源
        最近更新 更多