内部联接表替换ID值

时间:2017-02-21 21:28:19

标签: mysql database inner-join

我有一个团队表,每个团队都有一个这样的ID号......

TEAM ID      TEAM
1            Maitland
2            Orlando
3            Winter Park
4            Lake Mary

等等等等

我有一张桌子,仅使用ID号码列出时间表......

TEAM ID      Game1     Game2    Game3
1            2         3        4

是否可以INNER JOIN那些顶级到表格来创建一个表格,用这个正确的团队名称替换ID号码......

TEAM        Game1      Game2         Game3
Maitland    Orlando    Winter Park   Lake Mary

2 个答案:

答案 0 :(得分:0)

select t1.name as TEAM_ID, t2.name as Game1, t3.name as Game2, t4.name as Game3
from schedule s
     inner join teams t1 on t1.team_id = s.team_id
     inner join teams t2 on t2.team_id = s.Game1
     inner join teams t3 on t3.team_id = s.Game2
     inner join teams t4 on t4.team_id = s.Game3
     ...
     ...
     inner join teams t10 on t10.team_id = s.Game9;

答案 1 :(得分:0)

你有一个1:n的团队游戏关系。

如果您只是以正常形式存储 - teamid,游戏 - 以某种方式订购,例如按日期订购:

CREATE TABLE schedules (
    teamid INT,
    playing_with INT,
    order DATE

    FOREIGN KEY (teamid)
       REFERENCES teams(teamid)        
);

然后你将在两个联接中拥有它:

SELECT t.teamname AS team, t1.teamname AS PlayWithTeam
FROM schedules s
    INNER JOIN teams t ON s.teamid=t.teamid
    INNER JOIN teams t1 ON s.playing_with=t1.teamid
ORDER BY s.teamid, s.order;

Here's the Fiddle, check it