[英]two foreign keys to same primary key select statement MYSQL
first Table "teams" has TeamCode(varchar 5) and TeamName (varchar 20) second Table "season" has homeTeam (varchar 5) , Team2 (varchar 5), Gameday (date) 第一个表“ teams”具有TeamCode(varchar 5)和TeamName(varchar 20),第二个表“ season”具有homeTeam(varchar 5),Team2(varchar 5),Gameday(日期)
homeTeam & Team2 are FKs that are connected to TeamCode PK homeTeam和Team2是连接到TeamCode PK的FK
table: teams 表:团队
| | TeamCode |
TeamCode | TeamName |
队名|
|:-----------:|:--------------| |:-----------:|:-------------- |
| | 1 |
1 | USA |
美国|
| | 2 |
2 | UK |
英国|
| | 3 |
3 | JAPAN |
日本|
table: season 表:季节
each team plays the other once as a home team 每支球队都以主队的身份互相比赛一次
| 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|
I want a query that would display the Team names and the day they will play together 我想要一个查询,以显示球队名称和他们一起比赛的日期
So it should look like 所以应该看起来像
HomeTeam Name | Team2 Name | Gameday
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
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
Try this 尝试这个
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
SQL Server: 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: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.