MySql从两个表中选择多个并将其结果连接到第三个表

时间:2013-07-18 10:27:49

标签: mysql select join

我有三张桌子:玩家,玩家档案,种族。 Players和PlayersArchive表格结构完全相同。

在玩家和玩家档案中,我们有玩家ID和姓名。

在种族中我们有一排:

RaceID,Record1PlayerID,Record2PlayerID,Record3PlayerID,Record4PlayerID和Record5PlayerID

任务是选择整个Races表,但不是玩家ID字段,而是应该返回他们的名字。

e.g:

Races table:
RaceID: 1
Record1PlayerID: 2
Record2PlayerID: 1
Record3PlayerID: 0
Record4PlayerID: 0
Record5PlayerID: 0

Players table:
PlayerID: 1
Name: Jhon

PlayersArchive table:
PlayerID: 2
Name: Jack

result:
1     Jack     Jhon     NULL     NULL     NULL

2 个答案:

答案 0 :(得分:0)

您的数据结构存在两个问题。首先,你应该为每场比赛的球员设置一个单独的桌子,每个球员/比赛组合一排。将它们放在单行的单独列中是个坏主意。

第二个问题是将名称放在两个不同的表中。从您的问题来看,我无法判断players表和playersarchive表是否必要。所以,我认为没有必要存档。

解决方案是使用玩家信息从比赛表加入桌面:

select r.*,
       p1.name as name1,
       p2.name as name2,
       p3.name as name3,
       p4.name as name4,
       p5.name as name5
from races r left outer join
     players p1
     on r.record1playerid = p1.playerid left outer join
     players p2
     on r.record1playerid = p2.playerid left outer join
     players p3
     on r.record1playerid = p3.playerid left outer join
     players p4
     on r.record1playerid = p4.playerid left outer join
     players p5
     on r.record1playerid = p5.playerid left outer join

如果数据确实同时属于PlayersPlayersArchive,那么players可能需要:

     (select distinct playerid, name from ((select p.* from players) union all (select pa.* from playersarchive)) t) p1 . . .

这将两个表组合在一起以查找名称。

答案 1 :(得分:0)

这只能证明你所要求的解决方案。

Select RaceId, p1.Name AS Name1 From Races AS r
Left Join (
    Select * From Players 
    Union Select * From PlayersArchive
) AS p1 On r.Record1PlayerID = p1.PlayerID;

你应该在你的查询中重复这个左连接4次以获得所有5个名字。 请注意,对于大数据,这可能需要很长时间才能执行。