用SQL JOIN替换列

时间:2015-01-09 11:43:58

标签: mysql sql join foreign-keys

我有以下两个表

收藏

id    item    created_by    modified_by
---------------------------------------
1     Lips..  5             6

用户

id    first_name
----------------
5     Mark
6     Clare

我需要将created_by和modified_by列替换为与这些字段中的ID关联的first_name。

我目前正在使用以下代码

SELECT wishlist.*, user.first_name FROM wishlist
LEFT JOIN user ON user.id = wishlist.created_by

返回以下结果

id    item    created_by    modified_by    first_name
-----------------------------------------------------
1     Lips..  5             6              Mark

哪个好......我猜 - 但不是我需要的。

理想情况下,我想..

id    item    created_by    modified_by
---------------------------------------
1     Lips..  Mark          Clare

感谢任何帮助。谢谢:))

3 个答案:

答案 0 :(得分:3)

试试这个:

SELECT w.id,w.item, u1.first_name as created_by    , u2.first_name as modified_by
 FROM wishlist w
LEFT JOIN user u1 ON u1.id = wishlist.created_by
LEFT JOIN user u2 ON u2.id = wishlist.modified_by

答案 1 :(得分:1)

试试这个

select w.id,
(select First_name from Users 
where id=w.created_by) as created_by,

(select First_name from Users 
where id=w.modified_by) as modified_by

 from WhiteList w

答案 2 :(得分:1)

加入用户表两次,指定所需的确切列并相应地重命名它们:

SELECT wishlist.id, wishlist.item, u1.first_name AS created_by, u2.first_name AS modified_by FROM wishlist
LEFT JOIN user AS u1 ON u1.id = wishlist.created_by
LEFT JOIN user AS u2 ON u2.id = wishlist.modified_by