表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
如何为table1的 entered_by 加入这两个表格,而 modify_by 将替换为其在table2上具有相应ID的用户名。
感谢
答案 0 :(得分: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 :(得分: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