将列值与另一个没有公共列的表匹配

lymnna71  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(271)

例如

table a             table b
id     name         groupid    member1_id    member2_id    member3_id 
1      john          001         1            2             3
2      luke
3      james

我想要的结果是:

groupid   member1_id   name    member2_id      name    member3_id     name
001         1          john       2            luke       3           james

据我所知,要使用左或右联接,需要有匹配的列。我甚至不知道这是否可行。

zy1mlcev

zy1mlcev1#

你需要分开 join :

select b.*, a1.name as name1, a2.name as name2, a3.name as name3
from tableb b left join
     tablea a1
     on a1.id = b.member1_id left join
     tablea a2
     on a2.id = b.member2_id left join
     tablea a3
     on a3.id = b.member3_id;
z9zf31ra

z9zf31ra2#

我认为您只是在寻找多个连接:

select b.*, a1.name as name_1, a2.name as name_2, a3.name as name_3
from b left join
     a a1
     on b.member1_id = a1.id left join
     a a2
     on b.member2_id = a2.id left join
     a a3
     on b.member3_id = a3.id ;

它使用 left join 如果任何成员id列 NULL 或者无效。
总之,您应该重新审视您的数据结构。拥有多个具有相同信息的列通常不是一个好的做法。您的数据结构表明您需要一个连接/关联表。比如:

create table groupMembers (
    groupMemberId int auto_increment primary key,
    groupId int,
    MemberId int,
    constraint fk_groupMembers_groupId foreign key (groupId) references groups(groupId),
    constraint fk_groupMembers_memberId foreign key (memberId) references groups(memberId)
);

相关问题