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

旧巷老猫 提交于 2020-01-17 02:50:27

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/20087065/sql-join-one-column-serving-as-id-for-two-columns-in-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!