Skoota
Skoota

Reputation: 5290

SQL join for multiple columns with ids

I have two SQL tables. The first table stores a list of athletes with their id and name. For example:

athlete_id | first_name | last_name
-----------|------------|----------
1          | Matthew    | Reese
2          | Tiffanie   | Renz
3          | Tom        | Dow

etc...

The second table stores entries for a track (sprint) event, and the id of the athlete competing in each lane. For example:

event_id | lane1_athlete_id | lane2_athlete_id | lane3_athlete_id  
---------|------------------|------------------|-----------------
1        | 1                | 15               | 24
2        | 18               | 2                | 4
3        | 78               | 50               | 3

etc...

I need to create an SQL query which will return that second table, but with the athlete ids resolved to the athlete names. For example:

event_id | lane1_athlete | lane2_athlete | lane3_athlete  
---------|---------------|---------------|--------------
1        | Matthew Reese | Lesa Allain   | Nicole Spiers
2        | Emmy Bartol   | Tiffanie Renz | Louise Baier
3        | Zack Bui      | Norah Flagg   | Tom Dow

I imagine this involves a table join, but I can't get my head around the correct query. Any help would be appreciated.

Upvotes: 2

Views: 762

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

Join the second table to the first one, three times:

SELECT
    e.event_id,
    CONCAT(a1.first_name, ' ', a1.last_name) AS lane1_athlete,
    CONCAT(a2.first_name, ' ', a2.last_name) AS lane2_athlete,
    CONCAT(a3.first_name, ' ', a3.last_name) AS lane3_athlete
FROM events e
LEFT JOIN athletes a1
    ON e.lane1_athlete_id = a1.athlete_id
LEFT JOIN athletes a2
    ON e.lane2_athlete_id = a2.athlete_id
LEFT JOIN athletes a3
    ON e.lane3_athlete_id = a3.athlete_id;

Upvotes: 3

Related Questions