加入两个共享多对一Realtionship的SQL表

时间:2015-06-23 01:35:46

标签: mysql relational-database inner-join

您好我有两个表名为团队,另一个名为日程表

Schedule表具有以下属性:idawayhomedate ...其中away和home是Team表的外键。

Team表具有以下属性:nameid

我的目标是加入团队和计划,以便schedule.id,away,awayTeamName,home,homeTeamName,date都在同一个查询中。这就是我到目前为止所拥有的

SELECT  `GAME_ID` ,  `AWAY` , TEAM.NAME AS awayName,  `HOME`,  `LEVEL` , 
`LOCATION` ,  `DATE` 
FROM SCHEDULE
INNER JOIN TEAM ON SCHEDULE.AWAY = TEAM.TEAM_ID
OR SCHEDULE.HOME = TEAM.TEAM_ID

,我得到的输出是这样的

GAME_ID | AWAY | awayName | HOME | LEVEL | LOCATION | DATE
1       | 2    |  name1   | 3    |varsity| @home    | 06/22/2015

但我希望它看起来像这样

GAME_ID | AWAY | awayName | HOME | homeName| LEVEL | LOCATION | DATE
1       | 2    |  name2   | 3    | name3   |varsity| @home    | 06/22/2015

如果有人可以提供帮助我会很感激

2 个答案:

答案 0 :(得分:0)

您可以有多个加入。

SELECT  SCHEDULE.GAME_ID , away.AWAY, away.NAME AS awayName, home.HOME , home.NAME AS homeName, LEVEL , 
LOCATION , DATE 
FROM SCHEDULE
INNER JOIN TEAM as away ON SCHEDULE.AWAY = TEAM.TEAM_ID INNER JOIN TEAM as home ON
SCHEDULE.HOME = TEAM.TEAM_ID

会是这样的。

答案 1 :(得分:0)

 INNER JOIN TEAM as home ON SCHEDULE.HOME = TEAM.TEAM_ID

将此添加到查询的末尾,这将为您提供两个完全合法的内部联接。

如果将来有两个以上的表可以处理,你应该能够找到它。

inner joins on more than 2 table