两个外键引用相同的列

时间:2017-05-09 09:20:17

标签: mysql

我有两个表:Livestream和Team。

即时串流:

id_livestream int primary key

id_team1 int

id_team2 int

//我已将这两列引用到Team id_team列

团队:

id_team int primary key

name_team varchar(40)

image_team varchar(255)

我想从Team中为Livestream中的两个引用列选择name_team。 例如,我想展示类似的东西:

id_team1 | team1的名字| team1的形象| id_team2 |团队名称2 | team2的形象

2 个答案:

答案 0 :(得分:2)

您只需从Livestream表到Team表进行两次连接即可生成所需的输出:

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

我在此假设Livestream中出现的每个团队都会在Team表中的某个地方有一个条目。如果不是这种情况,并且您不希望结果集中出现NULL值,那么您可以切换为使用LEFT JOINCOALESCE()

答案 1 :(得分:1)

试试这个:

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

使用Team进行两次内连接可以解决问题。