Home > Back-end >  How to shownicknames instead of foreign key in SQL
How to shownicknames instead of foreign key in SQL

Time:08-19

So I'm practicing queries on SQL for educational purposes and I'm running queries from an NBA Basketball dataset. I want to make a query that will show me a date, home team, away team, and winner column. I can easily do this with this query:

SELECT game_id, SUBSTRING(date,0,11) AS Date_Only, team_id_home, team_id_away, team_id_winner
FROM game

However, these only show the id's of the teams. I don't want to see the foreign key id's of the teams, I want to see the nicknames for the teams which there's a separate table where the team id's and their nicknames are. How am I able to show the nicknames instead of the foreign keys? I've thought of a few things but there may be an easier way to do this. Appreciate the help. query result ER Diagram

CodePudding user response:

The query needs to join the table that contains the nicknames so that you can select the appropriate column, e. g.

SELECT game_id, SUBSTRING(date,0,11) AS Date_Only, 
   home_team.nickname AS home_team_nickname,
   away_team.nickname AS away_team_nickname,
   winner_team.nickname AS winner_team_nickname
FROM game 
  INNER JOIN team home_team ON game.team_id_home = home_team.team_id
  INNER JOIN team away_team ON game.team_id_away = away_team.team_id
  INNER JOIN team winner_team ON game.team_id_winner = winner_team.team_id
;
  • Related