简体   繁体   English

MySQL的两个左连接区分同一列

[英]MySQL Two Left Joins Distinguish Same Column

In the following query, I am selecting the one column from users and am expecting a join to take place on both follow_reconciliations user_id and followed_user_id column. 在以下查询中,我从用户中选择一个列,并希望在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) 

But, I need to know which query the ig_user_id comes from. 但是,我需要知道ig_user_id来自哪个查询。 How can I rename ig_user_id as an alias for each join? 如何将ig_user_id重命名为每个联接的别名? What is the best approach to this? 最好的方法是什么?

EDIT: Visually, this is how I want the results to return 编辑:视觉上,这就是我想要结果返回的方式

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

This query might be more in the direction of this. 此查询可能更倾向于此方向。 It returns the correct results as two rows but they are not renamed as two aliases. 它以两行的形式返回正确的结果,但不会将其重命名为两个别名。

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) 

Second Edit: This does the trick. 第二编辑:这可以解决问题。

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)

If I understand correctly (do I?) you only need one join: 如果我理解正确(可以吗?),您只需一个联接:

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

This gives me the results I am looking for: 这给了我想要的结果:

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)

If anyone has any performance suggestions, please chime in. 如果有人对性能有任何建议,请发出提示。

if i understand your question.. i'm sory if wrong.. 如果我明白你的问题..如果出错我很抱歉..

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)

this query provide you to rename or aliasing every column on table.. :) 此查询为您提供重命名或为表中的每个列加别名的可能性。:)

CMIIW II

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM