将同一表与不同的列联接

时间:2019-07-29 14:40:11

标签: sql join left-join right-join

嗨,这可能是一个愚蠢的问题,但是我有一个场景,其中我的tl1,tl2和tl3列引用的是下面的id列表结构,

id | name | email | tl1 | tl1 | tl3 |
1  | xyz  |x@g.com| null|  1  | 2   |
======================================
2  | abc  |z@g.com| null|  1  | 3   |
======================================
3  | def  |d@g.com| 1   |  2  |  4  |  

因此需要编写查询以获取tl1,tl2和tl3的名称,

如下所示

id | name | email | tl1 | tl1 | tl3 |
1  | xyz  |x@g.com| null| xyz | abc |
======================================
2  | abc  |z@g.com| null| xyz  | def|
======================================
3  | def  |d@g.com| xyz |  abc | ghi |  

我无法针对这种情况创建查询,我实际上创建了一个查询,但未获得唯一记录

这是我尝试过的查询

select distinct a.branch_code,a.email,a.partner_name,a.role_assigned,a.category,b.partner_name as tl1,
c.partner_name as tl2,d.partner_name as tl3
 from branch_master as a
 left join  branch_master  as b on b.tl1 = a.branch_code
 left join  branch_master as c on c.tl2 = a.branch_code
 left join  branch_master as d on d.tl3 = a.branch_code

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您需要将表自身保留3次:

select
  t.id, t.name, t.email,
  t1.name name1, t2.name name2, t3.name name3
from tablename t
left join tablename t1 on t1.id = t.tl1
left join tablename t2 on t2.id = t.tl2
left join tablename t2 on t3.id = t.tl3

答案 1 :(得分:0)

首先,这通常是一种错误的数据格式-通常,您希望这些值位于不同的表中。在某些情况下,跨列存储数据可能很有意义-例如,如果角色不同:submitted_byprocessed_byapproved_by。但是通常,您需要一个联结/关联表。

但是,解决问题的方法是多个左联接:

select t.*, t1.email as email1, t2.email as email2, t2.email as email3
from t left join
     t t1
     on t1.tl1 = t.id left join
     t t2
     on t2.tl2 = t.id left join
     t t3
     on t3.tl3 = t.id;