例如
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
据我所知要使用JOINS LEFT或RIGHT,您需要具有匹配的列。我什至不知道这是否有可能。
答案 0 :(得分:1)
您需要单独的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;
答案 1 :(得分:0)
我认为您只是在寻找多个联接:
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 ;
如果任何成员ID列为left join
或无效,则使用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)
);