[英]Select one Primary Key using multiple Foreign Keys from a table
So I don't know how to explain this properly using words so I'll just explain what I'm trying to do. 因此,我不知道如何使用单词正确地解释这一点,因此我只会解释我想做的事情。 I've made a database containing two tables, one being a list of NBA teams with a primary key next to it listing from 1-30. 我已经建立了一个包含两个表的数据库,一个表是NBA球队列表,其主键旁边是1-30。 The other table lists a schedule of games containing the columns Team1, Team2, and Winner, all of which are foreign keys (So they are numbers between 1-30). 另一个表列出了包含排行榜Team1,Team2和Winner的游戏时间表,所有这些列都是外键(因此它们是1到30之间的数字)。 I am trying to write a query which takes everyone from the schedule table but instead of taking the number 1-30 from the foreign keys, I want to have the actual team names. 我试图编写一个查询,从时间表表中获取所有人,但我不希望从外键中获取数字1-30,而是要具有实际的团队名称。
SELECT schedule.Date, schedule.GameTime, TEAMS.Team_name, TEAMS.Team_name, schedule.Team1_score, schedule.Team2_score, TEAMS.Team_name as Winner
FROM schedule
left join TEAMS on schedule.Team1 = TEAMS.Team_key
This is what I have written so far but I don't know how to compare schedule.Team2 = TEAMS.Team_key in order to get the other team's name, or to compare schedule.Winner = Teams.Team_key in order to get the winner's name. 这是我到目前为止编写的内容,但我不知道如何比较时间表。Team2= TEAMS.Team_key以获取其他团队的名称,或比较时间表。Winner= Teams.Team_key以获取获胜者的名称。
So for example right now I have: 例如,现在我有:
Date Time Team1 Team2 Team1Score Team2Score Winner 日期时间Team1 Team2 Team1Score Team2Score冠军
....... ........ Lakers Lakers ................... .................... Lakers 湖人湖人湖人......湖人
Instead of what I want which would be: 而不是我想要的是:
Date Time Team1 Team2 Team1Score Team2Score Winner 日期时间Team1 Team2 Team1Score Team2Score冠军
....... ........ Lakers Celtics ................... .................... Celtics 湖人凯尔特人队......凯尔特人
Thanks. 谢谢。
Well, you have three foreign keys, so you can do as follows: 好了,您有三个外键,因此可以执行以下操作:
SELECT t1.team_name AS team_one,
t2.team_name AS team_two,
t3.team_name AS winner FROM schedule s
INNER JOIN teams t1 ON s.team1 = t1.team_key
INNER JOIN teams t2 ON s.team2 = t2.team_key
INNER JOIN teams t3 ON s.winner = t3.team_key
You have 3 joins to the same table with different aliases. 您有3个连接到具有不同别名的同一表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.