0

我有一张这样的公司表

====================
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 上联接而不创建重复行。

4

1 回答 1

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 |
于 2013-07-09T15:27:39.077 回答