twyntee_trey
twyntee_trey

Reputation: 185

MySQL JOIN multiple columns with corresponding ID

I have two tables, one with names of teams, the other holds various selections made by users, each of which is represented by the team's team_id. I want to be able to display the actual team names for each, but can't figure out how the join would work.

Table 1

user_id(int), selection1(int), selection2(int), selection3(int)

Table 2

team_id(int), team_name(varchar)

Upvotes: 0

Views: 68

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271241

You need three joins:

select u.user_id, t1.team_name as team_name1, t2.team_name as team_name2,
       t3.team_name as team_name3
from users u left outer join
     teams t1
     on u.selection1 = t1.team_id left outer join
     teams t2
     on u.selection2 = t2.team_id left outer join
     teams t3
     on u.selection3 = t3.team_id;

Upvotes: 1

Related Questions