从一个表创建到查找表的多个联接

时间:2019-12-02 12:07:47

标签: sql join sql-server-2012

假设我在sql中有一个表A,数据在下面给出

enter image description here

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

enter image description here

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

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

3 个答案:

答案 0 :(得分:1)

您需要两次将表A JOIN移到表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

答案 1 :(得分:0)

您只想要两个join吗?

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;

答案 2 :(得分:0)

您只需要使用单独的连接两次引用查询表即可检索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