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

标签 mysql phpmyadmin

我正在尝试创建一个 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/

相关文章:

mysql - 当我尝试在 MariaDB 数据库上创建此函数(使用点数据类型)时,为什么会出现此错误?

mysql - PhpMyAdmin 配置/无法看到输入文本字段

php - 如何使用php、mysql更新数据库

php - 从mysql中提取数据的最有效方法是什么,使其格式如下:

MySQLNonTransientConnectionException/jdbc4.CommunicationsException 错误在使用 C3P0 时继续

mysql - 使用 phpmyadmin 中的触发器将选定的列从一个表复制到另一个表

php - 如何在php中更新记录?

mysql - 奇怪的 MySQL 弹出窗口 "Mysql Installer is running community mode"

phpmyadmin - 由于目标机器主动拒绝而无法建立连接

php - 我的mysql表结构应该如何?