两次加入同一张桌子

时间:2014-12-23 14:17:00

标签: mysql sql select join alias

我正在尝试在表格中列出一些数据。数据来自数据库,我的数据库中有3个表。

我正在尝试在这样的SQL语句中加入这三个表:

SELECT * FROM cases
LEFT JOIN users ON cases.fk_supporter = users.user_id
LEFT JOIN users ON cases.fk_creator = users.user_id

fk_supporter是用户的外键,因此是fk_creator,但不是同一个用户。如何正确地做到这一点?

5 个答案:

答案 0 :(得分:5)

您需要连接中相同表的唯一别名

SELECT * FROM cases c
LEFT JOIN users u1 ON c.fk_supporter = u1.user_id
LEFT JOIN users u2 ON c.fk_creator = u2.user_id

答案 1 :(得分:1)

您只需将 ALIAS 名称提供给表格

即可

试试这个:

SELECT * 
FROM cases c
LEFT JOIN users u1 ON c.fk_supporter = u1.user_id
LEFT JOIN users u2 ON c.fk_creator = u2.user_id;

答案 2 :(得分:0)

您可以在ALIAS表中使用users

SELECT * FROM cases
LEFT JOIN users supporter ON cases.fk_supporter = supporter.user_id
LEFT JOIN users creator ON cases.fk_creator = creator.user_id

答案 3 :(得分:0)

可能你会有LEFT JOIN之外的其他东西,尝试使用Alias名称的INNER JOIN作为@Saharsh和@Abhik提到 - 如:

SELECT * FROM cases C
INNER JOIN users U1 ON C.fk_supporter = U1.user_id
INNER JOIN users U2 ON C.fk_creator = U2.user_id

答案 4 :(得分:0)

好吧,我让它像这样工作:

SELECT 
supporter.usr AS supporter_usr, 
supporter.user_id as support_id,
creator.usr AS creator_usr, 
creator.user_id as creator_id,
cases.* FROM cases


LEFT JOIN users AS supporter 
ON supporter.user_id = cases.fk_supporter

LEFT JOIN users AS creator 
ON creator.user_id = cases.fk_creator