行中存在2个fk的normalise id

wfveoks0  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(301)

我正在尝试创建一个视图来规范“体育赛程”,但是在赛程表中,我有主队和客队的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)

fixtures有hometeamid,awayteamid团队有id和name
我尝试了一个子查询,但它返回多个结果。
任何帮助/建议都将不胜感激。
团队协作

pb3s4cty

pb3s4cty1#

你需要加入球队两次,一次是主队,一次是客场。
可以这样想:对于同一个表中的每个外键,都需要另一个联接。
虽然我不知道为什么你有多个连接到fixturef\u测试一个用户和一个完成。。。
而且,我也不喜欢把所有东西都放在后面。我宁愿只在保留/关键字时使用它,以使其更具可读性。

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

相关问题