2016-05-14 44 views
2

兩列假設我們有兩個表:INNER JOIN對於相同的外鍵

表TA

AID BID1 BID2 
-- ---- ---- 
01 01 02 
02 01 03 
03 02 01 

表TB

BID Name 
--- ---- 
01 FOO 
02 BOO 
03 LOO 

如果我想返回以下內容:

AID Name1 
-- ----- 
01 FOO 
02 FOO 
03 BOO 

I wr ite以下內容:

SELECT TA.AID, TB.Name as Name1 
FROM TB 
INNER JOIN TA on TB.BID = TA.BID1 

但是,我不知道如何返回對應於BID1和BID2的TB.Name。更具體地說我想返回以下內容:

AID Name1 Name2 
-- ----- ----- 
01 FOO BOO 
02 FOO LOO 
03 BOO FOO 

回答

7

你可以參加多次:

SELECT TA.AID, tb1.Name AS Name1, tb2.Name AS Name2 
FROM TA 
LEFT JOIN TB tb1 
    ON TA.BID1 = tb1.BID 
LEFT JOIN TB tb2 
    ON TA.BID2 = tb2.BID; 

注:LEFT OUTER JOIN將確保你總是從TA獲得的所有記錄,即使沒有匹配。

LiveDemo

+1

尼斯的答案,一爲'左外join' –

4

只需使用一個更加入

SELECT TA.AID, TB.Name as Name1, T1.Name as Name2 
FROM TB 
INNER JOIN TA on TB.BID=TA.BID1 
INNER JOIN TB T1 on T1.BID=TA.BID2; 
3

--one更多方式使用跨應用

select ta.aid,a1.*,a2.* 
    from table1 ta 
    cross apply(select tb.name from tableb tb where tb.aid=ta.bid1) a1 
    cross apply(select tb.name from tableb tb where tb.aid=ta.bid2) a2