0

我有三张桌子:Players、PlayersArchive、Races。Players 和 PlayersArchive 表的结构完全相同。

在 Players 和 PlayersArchive 中,我们有 PlayerID 和 Name。

在 Races 中,我们排成一行:

RaceID、Record1PlayerID、Record2PlayerID、Record3PlayerID、Record4PlayerID 和 Record5PlayerID

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

例如:

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
4

2 回答 2

0

您的数据结构有两个问题。第一个是你应该为每场比赛的球员提供一个单独的表格,每个球员/比赛组合有一排。将它们放在单行的不同列中是一个坏主意。

第二个问题是将名称放在两个不同的表中。根据您的问题,我无法判断playerstable 和playersarchivetable 是否都是必要的。所以,我假设存档是没有必要的。

解决方案是从比赛表加入到包含玩家信息的表中:

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 . . .

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

于 2013-07-18T11:12:32.037 回答
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 个名称。请注意,对于大数据,这可能需要很长时间才能执行。

于 2013-07-18T11:16:46.887 回答