多次在多列上使用JOIN

时间:2015-11-24 20:23:28

标签: sql sql-server join

我正在尝试找出在JOIN中使用MSSQL的最佳方式,以便执行以下操作:

我有两张桌子。一个表包含技术人员ID,一个数据集的示例如下:

+--------+---------+---------+---------+---------+
| tagid  | techBid | techPid | techFid | techMid |
+--------+---------+---------+---------+---------+
| 1-1001 |      12 |       0 |      11 |       6 |
+--------+---------+---------+---------+---------+

我有另一张表存储这些技术人员的名字:

+------+-----------+
| TTID | SHORTNAME |
+------+-----------+
|   11 | Steven    |
|   12 | Mark      |
|    6 | Pierce    |
+------+-----------+

如果第一个表中技术人员的ID为0,则该行没有该类型的技术人员(类型为B,P,F或M)。

我正在尝试提出一个查询,它会给我一个结果,其中包含表1中的所有数据以及表2中的短名称,如果有匹配的ID,那么结果将类似于以下内容:

+--------+---------+---------+---------+---------+----------------+----------------+----------------+----------------+
| tagid  | techBid | techPid | techFid | techMid | techBShortName | techPShortName | techFShortName | techMShortName |
+--------+---------+---------+---------+---------+----------------+----------------+----------------+----------------+
| 1-1001 |      12 |       0 |      11 |       6 | Mark           | NULL           | Steven         | Pierce         |
+--------+---------+---------+---------+---------+----------------+----------------+----------------+----------------+

我正在尝试使用JOIN来执行此操作,但我无法弄清楚如何多次连接多列到它看起来像

的位置
Select table1.tagid, table1.techBid, table1.techPid, table1.techFid, table1.techMid, table2.shortname 
FROM table1 
INNER JOIN table2 on //Dont know what to put here

2 个答案:

答案 0 :(得分:1)

你需要使用这样的左连接:

Select table1.tagid, table1.techBid, table1.techPid, table1.techFid, table1.techMid, 
      t2b.shortname, t2p.shortname, t2f.shortname, t2m.shortname, 
FROM table1 
LEFT JOIN table2 t2b on table1.techBid = t2b.ttid
LEFT JOIN table2 t2p on table1.techPid = t2p.ttid
LEFT JOIN table2 t2f on table1.techFid = t2f.ttid
LEFT JOIN table2 t2m on table1.techMid = t2m.ttid

答案 1 :(得分:0)

你只是多做左连接

select tech.techPid, techPname.SHORTNAME 
     , tech.techFid, techFname.SHORTNAME  
from tech 
left join techName as techPname 
     on tech.techPid = techPname.TTID 
left join techName as techFname 
     on tech.techFid = techFname.TTID