Mahdi H
Mahdi H

Reputation: 339

Two foreign keys referencing same column

I have two Tables : Livestream and Team.

Livestream:

id_livestream int primary key

id_team1 int

id_team2 int

// I had already referenced these two columns to Team id_team column

Team:

id_team int primary key

name_team varchar(40)

image_team varchar(255)

I want to select name_team from Team for both referenced columns in Livestream.. as example i want to show something like:

id_team1| name of team1| image of team1 | id_team2| name of team 2| image of team2

Upvotes: 0

Views: 745

Answers (2)

Bikash
Bikash

Reputation: 1938

Try this:

SELECT
    ls.id_team1,
    t1.name_team AS name_team_1,
    t1.image_team AS image_team_1,
    ls.id_team2,
    t2.name_team AS name_team_2,
    t2.image_team AS image_team_2
FROM Livestream ls
INNER JOIN Team t1
    ON ls.id_team1 = t1.id_team
INNER JOIN Team t2
    ON ls.id_team2 = t2.id_team

Inner join two times with Team does the trick.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

You can generate the output you want by simply doing two joins from the Livestream table to the Team table:

SELECT
    lm.id_team1,
    t1.name_team AS name_team_1,
    t1.image_team AS image_team_1,
    lm.id_team2,
    t2.name_team AS name_team_2,
    t2.image_team AS image_team_2
FROM Livestream lm
INNER JOIN Team t1
    ON lm.id_team1 = t1.id_team
INNER JOIN Team t2
    ON lm.id_team2 = t2.id_team

I assume here that every team appearing in Livestream will have an entry somewhere in the Team table. If this be not the case, and you don't want NULL values appearing in your result set, then you can switch to using a LEFT JOIN along with COALESCE().

Upvotes: 2

Related Questions