两个外键到同一个主键选择语句MYSQL

时间:2015-06-14 05:28:05

标签: mysql sql select foreign-keys

第一桌"球队"有TeamCode(varchar 5)和TeamName(varchar 20) 第二桌"赛季"有homeTeam(varchar 5),Team2(varchar 5),Gameday(日期)

homeTeam& Team2是连接到TeamCode PK的FK

表:团队

| TeamCode | TeamName |
|:-----------:|:-------------- |
| 1 |美国|
| 2 |英国|
| 3 | JAPAN |

表:季节

每支球队作为主队参加另一支球队

| Team1 | Team2 |Gameday
|:-----:|:------|:------|  
| 1     | 2     | 7  jan|
| 1     | 3     | 14 jan|
| 2     | 1     | 21 jan|  
| 2     | 3     | 28 jan|  
| 3     | 1     | 4  feb|
| 3     | 2     | 11 feb|

我想要一个显示团队名称和他们将一起玩的日子的查询

所以看起来应该是

HomeTeam Name |   Team2 Name  |  Gameday

4 个答案:

答案 0 :(得分:1)

SELECT
    ht.TeamName,
    at.TeamName,
    s.GameDay
FROM
    teams AS ht
    INNER JOIN season AS s ON ht.TeamCode = s.Team1
    INNER JOIN teams AS at ON s.Team2 = at.TeamCode

答案 1 :(得分:1)

declare @t table (Teamid int,name varchar(10))
insert into @t (Teamid,name)values (1,'usa'),(2,'uk'),(3,'japan')
declare @tt table (Team1 int,Team2 int,gameday varchar(10))
insert into @tt(Team1,Team2,gameday)values (1,2,'7 jan'),(1,3,'14 jan'),(2,1,'21 jan'),(2,3,'28 jan'),(3,1,'4 feb'),(3,2,'11 feb')

select (select name from @t where Teamid = t.Team1) Home,
       (select name from @t where Teamid = t.Team2) Guest,
       gameday
from @tt t

答案 2 :(得分:1)

试试这个

SELECT
     T1.Name As Host ,
     T2.Name As Guest,
     S.Date 
FROM [dbo].[Season] as S
Inner Join [dbo].[Team] as T1 on S.HostTeam = T1.ID
Inner Join [dbo].[Team] as T2 on S.GuestTeam = T2.ID

答案 3 :(得分:0)

SQL Server:

SELECT t1.TeamName AS [HomeTeam Name],
       t2.TeamName AS [Team2 Name],
       s.Gameday
  FROM Season s
  JOIN Teams t1 ON t1.TeamCode = s.homeTeam -- or s.Team1 (unclear in your post which is the right column name)
  JOIN Teams t2 ON t2.TeamCode = s.Team2

MySQL的:

SELECT t1.TeamName AS `HomeTeam Name`,
       t2.TeamName AS `Team2 Name`,
       s.Gameday
  FROM Season s
  JOIN Teams t1 ON t1.TeamCode = s.homeTeam -- or s.Team1 (unclear in your post which is the right column name)
  JOIN Teams t2 ON t2.TeamCode = s.Team2