[英]Two foreign keys referencing same column
I have two Tables : Livestream and Team. 我有两个表:Livestream和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列
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: 我想从团队中为Livestream中的两个引用列选择name_team。例如,我想显示以下内容:
id_team1| id_team1 | name of team1| 队名1 | image of team1 | team1的图片| id_team2| id_team2 | name of team 2| 小组2的名称| image of team2 team2的图片
You can generate the output you want by simply doing two joins from the Livestream
table to the Team
table: 您只需通过从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
I assume here that every team appearing in Livestream
will have an entry somewhere in the Team
table. 我在这里假设出现在Livestream
中的每个团队在“ Team
表中的某个位置都有一个条目。 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()
. 如果不是这种情况,并且您不希望在结果集中出现NULL
值,则可以切换到使用LEFT JOIN
和COALESCE()
。
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. 与Team
两次内联会达到目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.