如何在MySQL中修复此简单的外键错误

时间:2019-06-10 08:27:10

标签: mysql foreign-keys

该如何查询?关于简单的外键查询

这是我正在做的一个小项目

例如,这些球员:

玩家:

| PlayerId | name | team_TeamId |

| 1        | john | 1           |
| 2        | myke | 1           |
| 3        | carl | 2           |

这支队伍:

团队:

| TeamId | name        |

| 1      | Arsenal     |
| 2      | Real Madrid |
SELECT player.name, team.name
FROM player, team
WHERE player.team_TeamId = 1

此查询向我显示了此信息:

| name | team.name   |

| john | Arsenal     |
| myke | Arsenal     |
| john | Real Madrid |
| myke | Real Madrid |

此查询“有效”(很显然这是不正确的形式):

SELECT *
FROM player, team
WHERE player.team_TeamId = 1 AND team.TeamId = 1
| name | team.name   |

| john | Arsenal     |
| myke | Real Madrid |

我希望只有teamId = 1的球员,但实际输出是teamId = 1的球员,但对所有球队都重复。

2 个答案:

答案 0 :(得分:0)

SELECT *
FROM player
JOIN team ON player.team_TeamId = team.TeamId
WHERE team.TeamId = 1

答案 1 :(得分:0)

我可能不知道正确的答案。从最后我看到的是,您尝试选择的方式没有任何关系。但是您可以通过在两个表中添加两个虚拟列来解决。

select pt.name,tt.name from (SELECT player.*, @i:=@i+1  AS rowNum 
 FROM player , (SELECT @i:=0) AS temp
WHERE player.team_TeamId = 1) as pt LEFT JOIN
(SELECT team.*, @j:=@j+1  AS rowNum  from team  , (SELECT @j:=0) AS temp ) as tt  on 
pt.rowNum = tt.rowNum