TopicsCheat sheetLessons
Lurndo › Topics › Multiple joins

Learn SQL: Multiple joins

More than two tables

"Who scored, against whom, and for which team?" Yasmine wants a top scorers list for the club magazine. It's spread across four tables.

JOIN after JOIN

You can chain as many JOINs as you like. Each JOIN gets its own ON. Here every goal gets the scorer's name and the opponent of that match.

Follow the keys: goals points at players and at matches.

SELECT p.name, g.minute, m.opponent FROM goals g JOIN players p ON g.player_id = p.id JOIN matches m ON g.match_id = m.id
Result
nameminuteopponent
Yannick Diallo12SK Molenhoek
Bram De Smet55SK Molenhoek
Yannick Diallo78SK Molenhoek
Charlotte Maes30Rapid Heidebos
Nora Aerts71Rapid Heidebos
Lars Willems8KV De Vaart
Lars Willems44KV De Vaart
Mila Jacobs60KV De Vaart

A chain of keys

Sometimes you have to go through a table in between. A goal doesn't know which team it was for, but it does know which match. And the match knows which team played. So you follow the chain goals → matches → teams.

And you can combine it all with what you already know, like GROUP BY.

SELECT t.name, COUNT(*) AS goals FROM goals g JOIN matches m ON g.match_id = m.id JOIN teams t ON m.team_id = t.id GROUP BY t.name
Result
namegoals
Men A10
U112
U137
U154
Women A6

Try it yourself

Make the top scorers list. For each player, show the name, the team name and the number of goals.

Ready for more?

The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.

Start the lesson
← PreviousRIGHT and FULL JOINNext →Joining a table to itself
SQL topicsCheat sheetExcelLeaderboardAccountPrivacyNederlands