简体   繁体   中英

SQL join - one column serving as ID for two columns in another table

Okay, maybe I've absolutely goofed on the thought process behind this and I need put in my place, or maybe I'm not far off.

I have one table called TEAMS with two columns: teamID and teamName. I then have another table called WEEK12 with three columns: gameID, homeID and awayID.

I thought maybe I could use the teamID in the homeID and awayID columns for the WEEK12 table and then join that with the TEAMS table to match those two columns up with the team names. Unfortunately, I'm not having any luck. I can join and get team names to match with homeID or awayID, but I can't do both.

Any help is greatly appreciated!

SELECT w.gameID,
       h.teamName AS 'Home Team',
       a.teamName AS 'Away Team' 
FROM WEEK12 AS w 
     LEFT JOIN TEAMS AS h 
               ON w.homeID=h.teamID 
     LEFT JOIN TEAMS AS a 
               ON w.awayID=a.teamID

You should be able to join to the same table twice in the same query. Performance hit (twice the lookups) but it should work.

SELECT home.teamName as homeTeam, away.teamName as awayTeam, week.gameID
FROM week12 week
INNER JOIN teams home ON week.homeID = home.teamID
INNER JOIN teams away ON week.awayID = away.teamID

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