用 SQL JOIN 替换列

Replace columns with SQL JOIN

我有下面两个表

心愿单

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

用户

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

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

我目前正在使用以下代码

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

其中returns结果如下

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

没关系..我想 - 但不是我需要的。

理想情况下,我想..

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

感谢任何帮助。谢谢:)

试试这个

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

试试这个:

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

加入用户 table 两次,指定您想要的确切列并相应地重命名它们:

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