SQL:针对不同的行从一个表中检索主表两次
我有两张桌子: 表1:团队参与者SQL:针对不同的行从一个表中检索主表两次,sql,self-join,Sql,Self Join,我有两张桌子: 表1:团队参与者 Primary Key(Id) Name Country TeamParticipant表的示例 23,Brazil,Brazil 25,England,England 表2:比赛 Primary Key: Id EventId Foreign Key: TeamParticipantId1// Primary Key of table TeamParticipant Foreign Key2: TeamParicipantId2//Primary Key
Primary Key(Id)
Name
Country
TeamParticipant表的示例
23,Brazil,Brazil
25,England,England
表2:比赛
Primary Key: Id
EventId
Foreign Key: TeamParticipantId1// Primary Key of table TeamParticipant
Foreign Key2: TeamParicipantId2//Primary Key of table TeamParticipant
匹配表的示例
1,1,23,25
我需要合并这些表并生成以下输出
Id,EventId, Country1(TeamParticipantId1), Country2(TeamParticipantId2)
我需要生成的输出示例:
1,1,Brazil, England
我被使用连接的sql逻辑卡住了
请告知您需要使用不同的别名加入表
TeamParticipant
两次
试试这个:
SELECT M.id,M.eventid, T1.Country as Country1,T2.Country as Country2
FROM Matches M JOIN
TeamParticipant T1 ON M.TeamParticipantId1=T1.id JOIN
TeamParticipant T2 ON M.TeamParticipantId2=T2.id
结果:
ID EVENTID COUNTRY1 COUNTRY2
1 1 Brazil England
请参阅中的结果
说明:
这里,表TeamParticipantId1
和TeamParticipantId2
上的表Matches
分别与具有不同别名的T1
和T2
连接两次