简体   繁体   中英

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. 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). 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.

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.

So for example right now I have:

Date Time Team1 Team2 Team1Score Team2Score Winner

....... ........ Lakers Lakers ................... .................... Lakers

Instead of what I want which would be:

Date Time Team1 Team2 Team1Score Team2Score Winner

....... ........ 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM