我正在尝试创建一个标准化“运动装置”的视图,但是我在主题乐队表格中连续拥有主队和客队的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和名字
我尝试了一个子查询,但它返回多个结果。
任何帮助/建议表示赞赏。
你需要两次加入球队,一次是主队,一次是外出。
可以这样想:对于每个外键,你需要另一个连接。
虽然我不确定为什么你有多个连接到fixturef_testing一个用户和一个完成...
而且,我不喜欢把所有东西都放在后面。当我有一个reserved / keyword来使它更具可读性时,我宁愿只使用它。
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