简体   繁体   English

SQL连接-一列用作另一表中两列的ID

[英]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.

相关问题 如何将SQL表中的2列连接到另一个SQL表中的一列? - How to join 2 columns in a SQL table to one column in another SQL table? 将一个表的两列连接到另一表的一列 - Join two columns from one table to one column from another 将一个表的两列连接到另一表的同一列 - Join two columns of one table to the same column of another table Sequelize将一张表的两列连接到另一张表的同一列 - Sequelize join two columns of one table to the same column of another table PHP连接两个表,其中一个表中的两列包含from_ID和to_ID引用另一表中的id - PHP join two table where two column in one table contains from_ID and to_ID refer to id in another table 两列引用另一个表中的一个ID - Two columns refer to one id in another table 如何将一个表中的两个或更多列与另一个表中的一个列联接在一起,即使第一个表列中的值为NULL - How to join two or more columns from one table with one column from another table, even there are NULL values in first table columns 从两个表插入到一个表的SQL语句(使用来自另一个无连接条件的表的ID) - SQL Statement to INSERT into one table from two (using id from another w/no join criteria) sql连接中存在相同名称的两列时,如何从一个表列获取值 - How to get value from one table column when two columns of the same name exist in an sql join 在一个中连接两个表,在另一个表中有一个id和多个id - join two tables in one with one id and multiple ids in another table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM