简体   繁体   中英

Inner joins on SQL multiple rows

I've got 2 tables in my SQL database:

**teams**
id
name
country

**games**
id
date
hometeamid (hometeam country)
awayteamid (awayteam country)
score

Now i want to get the games with all their data, but instead of getting hometeamid's I want to get their names and countries by getting them from the teams table by some sort of inner join.

Anyone know how to get 4 variables in 1 query by id from another table (team)?

select * from games inner join teams on games.hometeamid = teams.id;

This will create a table that matches each team to each game that exists. If there is a game without the team OR a team without a game, they will be omitted since INNER JOIN needs both to match.

You should join the table team two time one for hometeam and one for awayteam

select g.date, g.hometeamid, t1.name hometeam, t2.name  awayteam
from games g 
inner join teams t1 on g.hometeamid = t1.id
INNER JOIN teams t2 on g.hometeamid = t2.id

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