Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to make multiple joins to the same column of a table without overriding results?

Tags:

sql

join

mysql

I have a table of basketball matches and a table of basketball teams like this:

MATCHES:
ID   |   HOME_TEAM_ID  |  AWAY_TEAM_ID | SCORE_HOME | SCORE_AWAY
----------------------------------------------------------------
1    |       20        |       21      |     80     |    110
2    |       12        |       10      |     96     |     90


TEAMS:
ID   |   NAME
-------------------------
20   |   BULLS
21   |   KNICKS

Given a match ID, I would like to retrieve both the score and the team names. How do I make a JOIN that retrieves both team names from the teams table?

I have tried:

SELECT *
FROM matches AS m
JOIN teams AS t1 ON t.id = m.home_team_id
JOIN teams AS t2 ON ti.id = m.away_team_id
WHERE m.id = 1

...but here the result from the second JOIN statement seems to override the one from the first, so I only get one name:

[id] => 1
[score_home] => 80
[score_away] => 110
[name] => KNICKS

I have also tried:

SELECT *
FROM matches AS m
JOIN teams AS t ON (t.id = m.home_team_id OR t.id = m.away_team_id)
WHERE m.id = 1

...which returns two results :

[id] => 1
[score_home] => 80
[score_away] => 110
[name] => BULLS

and

[id] => 1
[score_home] => 80
[score_away] => 110
[name] => KNICKS

I would like to make a query that returns something like this

[id] => 1
[score_home] => 80
[score_away] => 110
[name_home_team] => BULLS
[name_home_team] => KNICKS

Is that possible?

like image 525
acrmuui Avatar asked Oct 16 '12 10:10

acrmuui


3 Answers

SELECT
    Matches.ID,
    Matches.Score_Home,
    Matches.Score_Away,
    HomeTeam.Name Home_Team_Name,
    AwayTeam.Name Away_Team_Name
FROM
    Matches
    INNER JOIN Teams HomeTeam ON Matches.Home_Team_ID = HomeTeam.ID
    INNER JOIN Teams AwayTeam ON Matches.Away_Team_ID = AwayTeam.ID
like image 184
Tobsey Avatar answered Nov 15 '22 13:11

Tobsey


you just have to name the column name with alias names

SELECT m.ID,
       m.SCORE_HOME,
       m.SCORE_AWAY,
       t1.NAME as name_home_team,
       t2.NAME as name_home_team
FROM MATCHES AS m
JOIN teams AS t1 ON t1.id = m.home_team_id
JOIN teams AS t2 ON t2.id = m.away_team_id
WHERE m.id = 1
like image 36
Joe G Joseph Avatar answered Nov 15 '22 11:11

Joe G Joseph


   select  m.ID,
           (select NAME from TEAM where id=m.HOME_TEAM_ID) HOME_TEAM_NAME,
           m.SCORE_HOME,
           (select NAME from TEAM where id=m.AWAY_TEAM_ID) AWAY_TEAM_NAME,    
           m.SCORE_AWAY 
    from 
    MATCHES m
    where m.ID=1
like image 27
AnandPhadke Avatar answered Nov 15 '22 13:11

AnandPhadke