gpt4 book ai didi

mysql - 规范化行中存在 2 个 FK 的 ID

转载 作者:行者123 更新时间:2023-11-29 16:32:45 25 4
gpt4 key购买 nike

我正在尝试创建一个 View 来标准化“体育赛事”,但是我在赛程表中连续显示了主队和客队的 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)

赛程有主队和客队id团队有 ID 和名称

我尝试了子查询,但它返回多个结果。

感谢任何帮助/建议。

Teams Fixtures

最佳答案

您需要加入球队两次,一次为主队,一次为客队。

这样想:对于同一个表的每个外键,您需要另一个连接。

虽然我不确定为什么你有多个连接到fixturef_testing,一个用于用户,一个用于完成......

此外,我不喜欢将所有内容都放在后面的勾号中。我宁愿只在有保留/关键字时使用它以使其更具可读性。

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

关于mysql - 规范化行中存在 2 个 FK 的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53785328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com