我正在尝试创建一个用于标准化“运动器材”的视图,但是我在灯具表中同时具有主队和客队的ID。在尝试对它们进行标准化时,如何获得相关团队的团队名称?
select cast(`f`.`datetime` as date) AS `date`
, cast(`f`.`datetime` as time) AS `time`
, (select `t`.`name`
from (`fixturef_testing`.`teams` `t`
join `fixturef_testing`.`fixtures` `f`
on((`f`.`hometeamid` = `t`.`id`)))
where (`t`.`id` = `f`.`hometeamid`)) AS `hometeam`
, (select `t`.`name`
from (`fixturef_testing`.`teams` `t`
join `fixturef_testing`.`fixtures` `f`
on((`f`.`awayteamid` = `t`.`id`)))
where (`t`.`id` = `f`.`awayteamid`)) AS `awayteam`
, `u`.`name` AS `referee`,`c`.`name` AS `competition`
from ((`fixturef_testing`.`fixtures` `f`
left join `fixturef_testing`.`users` `u`
on((`u`.`id` = `f`.`refereeid`)))
left join `fixturef_testing`.`competition` `c`
on((`c`.`id` = `f`.`competitionid`)))
where (`f`.`active` = 1)
固定装置有hometeamid和awayteamid 团队有ID和名称
我尝试了一个子查询,但是它返回了多个结果。
任何帮助/建议都值得赞赏。
答案 0 :(得分:0)
您需要两次加入团队,一次加入主队,一次离开。
这样想:对于同一张表,每个外键都需要另一个联接。
尽管我不确定为什么您要对fixff_test进行多次联接,然后为用户一次进行联接,然后为完成进行一次联接...
此外,我也不喜欢把所有东西都放在后面。我宁愿仅在有保留/关键字以使其更具可读性时使用它。
SELECT cast(f.`datetime` as date) AS `date`
, cast(f.`datetime` as time) AS `time`
, HT.Name hometeam
, AT.Name awayteam
, u.name AS referee
, c.name AS competition
FROM fixturef_testing.fixtures f
--Are the next 2 joins really needed?--
LEFT JOIN fixturef_testing.users u
on u.id = f.refereeid
LEFT JOIN fixturef_testing.competition c
on c.id = f.competitionid
--Not sure what the above joins are for...
--Get the table Teams record for the home team
LEFT JOIN Teams HT
on HT.ID = f.hometeamID
--Get the table Teams record for the away team
LEFT JOIN Teams AT
on AT.ID = f.awayTeamID
WHERE f.active = 1