Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

sql - How to distinguish these two ID requests when joining tables?

SQL noob here. I have a database of soccer matches that I am trying to learn/practice SQL with.

In one table (called "Match") there is the match_api_id, date, home_team_api_id, away_team_api_id, home_team_goal, away_team_goal. In another table (called "Team") there is the team_api_id, team_long_name.

Right now I am trying to do a query to show the ID of the match, the date, the home team's name, and the away team's name.

SELECT M.match_api_id, M.date, T.team_long_name, T.team_long_name
FROM Match M
JOIN Team T ON (M.home_team_api_id = T.team_api_id)
JOIN Team T ON (M.away_team_api_id = T.team_api_id)
LIMIT 10

This code worked when I only used one join (the first one) to show the home team's name. However, when I add the second join it gives me the ambiguous column name error. How do I alter this code so that I can also display the away team's name?

question from:https://stackoverflow.com/questions/66049584/how-to-distinguish-these-two-id-requests-when-joining-tables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

YOu need different table aliases. Otherwise T is ambiguous:

SELECT M.match_api_id, M.date, TH.team_long_name, TA.team_long_name
FROM Match M JOIN 
     Team TH
     ON M.home_team_api_id = TH.team_api_id JOIN
     Team TA
     ON M.away_team_api_id = TA.team_api_id;
LIMIT 10

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...