[英]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. 我有一个名为TEAMS的表,其中有两列:teamID和teamName。 I then have another table called WEEK12 with three columns: gameID, homeID and awayID. 然后,我还有另一个名为WEEK12的表,该表具有三列:gameID,homeID和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. 我以为也许可以在WEEK12表的homeID和awayID列中使用teamID,然后将其与TEAMS表结合起来,以使这两列与团队名称匹配。 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. 我可以加入并获得与homeID或awayID匹配的团队名称,但是我不能两者都做。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.