在两列上加入一个表

时间:2013-07-09 15:24:00

标签: sql-server-2005 join

我有这样的公司表

====================
companyid, companyname
  2         com A
  3         com B
  4         com C
  5         com D
  6         com E

我运行了一个查询,其结果数据集如下所示

====================================
name |  InvoiceTo_ID |   ProviderID 
------------------------------------
p1          2               3
p2          2               4
p3          6               3
p4          5               6

现在我想要的是将我的数据集与上面的companies表联系起来,以便InvoiceTo_ID得到一个可信赖的名称,对于ProviderID,我得到一个相应的名称。这是最终结果

======================================================================
name |  InvoiceTo_ID |   ProviderID | InvoiceTo_Name |  ProviderName 
----------------------------------------------------------------------
p1          2               3               com A             com B
p2          2               4               com A             com C
p3          6               3               com E             com B
p4          5               6               com D             com E

如何构建我的连接,以便它连接到invoiceID和ProviderID,而不会创建重复的行。

1 个答案:

答案 0 :(得分:0)

您需要将查询加入companies表两次才能获得最终结果。一个联接将获得InvoiceTo_Name,第二个联接将获得ProviderName

select q.name,
  q.InvoiceTo_ID,
  q.ProviderID,
  c1.companyname InvoiceTo_Name,
  c2.companyname ProviderName
from yourquery q
left join companies c1
  on q.InvoiceTo_ID = c1.companyid
left join companies c2
  on q.ProviderID = c2.companyid;

SQL Fiddle with Demo。这给出了一个结果:

| NAME | INVOICETO_ID | PROVIDERID | INVOICETO_NAME | PROVIDERNAME |
--------------------------------------------------------------------
|   p1 |            2 |          3 |          com A |        com B |
|   p2 |            2 |          4 |          com A |        com C |
|   p3 |            6 |          3 |          com E |        com B |
|   p4 |            5 |          6 |          com D |        com E |