我试图找出在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)。
我正在尝试提出一个查询,如果有匹配的ID,将给出一个结果,该查询将包含表1中的所有数据以及表2中的短名称,因此结果如下所示:
+--------+---------+---------+---------+---------+----------------+----------------+----------------+----------------+
| 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发布于 2015-11-24 20:28:42
您需要像这样使用左联接:
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发布于 2015-11-24 20:32:16
你只需做多个左加入
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.TTIDhttps://stackoverflow.com/questions/33903106
复制相似问题