2016-04-01 71 views
1

我想連接兩個表,但是要在其他表中的兩個字段之上。來自一張桌子的兩列由不同的ID組成。 我的表結構如下:SQL Multiple與相同字段的連接

單位

+---+---------+----+ 
| Uid | UnitName 
+---+--------------+ 
| 1 | Unit A  | 
| 2 | Unit B  | 
| 3 | Unit C  | 
+----+---------+---+ 

+---+---------+-------------------+------------+------+ 
| Pid | PerName   | PerUnit | PreviousPerUnit | 
+---+---------+-------------------+------------+------+ 
| 1 | John    | 1  | 3   | 
| 2 | Alice   | 2  | 1   | 
| 3 | Mel    | 1  | 1   | 
+----+---------+------------------+------------+------+ 

所以我想輸出

+---+---------+-------------------+------------+----+ 
| # | PerName   | UnitName | PreUnitName | 
+---+---------+-------------------+------------+----+ 
| 1 | John    | Unit A  | Unit C  | 
| 2 | Alice   | Unit B  | Unit A  | 
| 3 | Mel    | Unit A  | Unit A  | 
+----+---------+------------------+------------+----+ 

我怎樣才能得到這個輸出?

回答

0

試試這個

SELECT p.PerName,perUnitTable.UnitName,PreviousUnitTable.UnitName 
FROM Person p 
INNER JOIN Units perUnitTable ON p.PerUnit=perUnitTable.Uid 
INNER JOIN Units PreviousUnitTable ON p.PerUnit=PreviousUnitTable.Uid 
+0

感謝JaydipJ你的回答。沒關係。 – mbayrak

0

需要兩個JOIN S:

SELECT 
    [#]   = p.Pid, 
    Pername  = p.PerName, 
    UnitName = u1.UnitName, 
    PerUnitName = u2.UnitName 
FROM Persons p 
INNER JOIN Units u1 
    ON u1.Uid = p.PerUnit 
INNER JOIN Units u2 
    ON u2.Uid = p.PreviousPerUnit 
+0

菲利克斯感謝烏拉圭回合的答案。沒關係。 – mbayrak