MySQL两个左连接区分同一列

时间:2014-03-24 03:38:45

标签: php mysql database

在以下查询中,我从用户中选择了一列,并期望在follow_reconciliations user_id和followed_user_id列上进行连接。

SELECT u.ig_user_id FROM users u 
LEFT JOIN follow_reconciliations f ON (f.followed_user_id = u.user_id) 
LEFT JOIN follow_reconciliations f2 ON (f2.user_id = u.user_id) 

但是,我需要知道ig_user_id来自哪个查询。如何将ig_user_id重命名为每个连接的别名?最好的办法是什么?

编辑:从视觉上看,这就是我希望结果返回的方式

+------------+---------------------+
| ig_user_id | followed_ig_user_id |
+------------+---------------------+
| 15325      | 5295                |
+------------+---------------------+

此查询可能更符合此方向。它将正确的结果作为两行返回,但它们不会重命名为两个别名。

SELECT u.ig_user_id AS ig_user_id FROM users u LEFT JOIN follow_reconciliations f ON (f.user_id = u.user_id) 
UNION
SELECT u2.ig_user_id AS followed_ig_user_id FROM users u2 LEFT JOIN follow_reconciliations f2 ON (f2.followed_user_id = u2.user_id) 

第二次编辑:这就是诀窍。

SELECT u.ig_user_id AS ig_user_id, u2.ig_user_id AS followed_user_id
FROM follow_reconciliations f
LEFT JOIN users u ON (u.user_id = f.user_id)
LEFT JOIN users u2 ON (f.followed_user_id = u2.user_id)

3 个答案:

答案 0 :(得分:0)

如果我理解正确(是吗?)你只需要一次加入:

SELECT 
  ig_user_id,
  f.followed_user_id as followed_ig_user_id
FROM users u
LEFT JOIN follow_reconciliations f USING (user_id)

答案 1 :(得分:0)

这给了我正在寻找的结果:

SELECT u.ig_user_id AS ig_user_id, u2.ig_user_id AS followed_user_id
FROM follow_reconciliations f
LEFT JOIN users u ON (u.user_id = f.user_id)
LEFT JOIN users u2 ON (f.followed_user_id = u2.user_id)

如果有人有任何表现建议,请加入。

答案 2 :(得分:0)

如果我理解你的问题......如果错误的话,我就知道了......

SELECT u.ig_user_id,xx.followed_user_id FROM users u LEFT JOIN (SELECT * FROM follow_reconciliations f) as xx ON (xx.followed_user_id = u.user_id) LEFT JOIN (SELECT * FROM follow_reconciliations f2) as yy ON (yy.user_id = u.user_id)

此查询允许您重命名或别名表上的每一列。:)

CMIIW