2015-11-24 40 views
0

我試圖找出最佳的方式,使用MSSQL一個JOIN爲了做到以下幾點:使用JOIN上多列多次

我有兩個表。一個表包含技師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 

回答

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 
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 
+0

霍根首次 - 給他檢查 – Paparazzi

+0

我快!小心! – Hogan