2013-10-31 19 views
0

我有表是這樣的:SQL:加入2表,並更改ID,以用戶名

表1:

id | item_name | entered_by | modify_by 
1 | banana |  2  | 1 
2 | apple  |  4  | 3 
3 | orance |  1  | 1 
4 | pineapple |  5  | 3 
5 | grape  |  6  | 1 

表2:

id | username 
1 | admin 
2 | jack 
3 | danny 
4 | dummy 
5 | john 
6 | peter 

如何加入這兩個表,表1的entered_by and modify_by被他們的用戶名和id相應地替換爲table2。

感謝

回答

5

嘗試了這一點:

SELECT t1.id, t1.item_name, 
    t2enteredBy.username enteredBy, 
    t2modifyBy.username modifyBy 
FROM table1 t1 
JOIN table2 t2enteredBy ON t1.entered_by = t2enteredBy.id 
JOIN table2 t2modifyBy ON t1.modify_by = t2modifyBy.id 

小提琴here

總之,您需要每個這些字段的連接。這就是爲什麼table2有雙加入的原因。

+1

只是工作正常,真棒,謝謝 – Teddybugs

0
SELECT tmp.id, item_name, tmp.username as entered, b.username as modify 
FROM (SELECT t.id, item_name, username, modify_by 
    FROM table1 t 
    INNER JOIN table2 a 
    ON t.entered_by=a.id 
)tmp 
INNER JOIN table2 b ON tmp.modify_by=b.id