gpt4 book ai didi

mysql - sql join 返回两个相同的值

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

我在mysql中有两个表:matchesteamsmatches有列home_team away_team 与表 teams.team_id 中的 fk 连接。我想在 home_team 中获取这些名称away_team 而不是他们的 id ...我已经尝试过这个,但它两次返回相同的值..我做错了什么,但我无法弄清楚。

代码

SELECT matches.home_team, matches.away_team, teams.name as home, teams.name as 
away FROM matches left join teams ON matches.home_team = teams.team_id
left join teams as t ON matches.away_team = t.team_id

第一个值是正确的,但第二个值不正确。

最佳答案

您的别名已关闭。您在当前查询中两次引用同一个teams 表。尝试这个版本,它使用正确的别名来区分两个连接的 teams 表。

SELECT
m.home_team,
m.away_team,
t1.name AS home,
t2.name AS away
FROM matches m
LEFT JOIN teams t1
ON m.home_team = t1.team_id
LEFT JOIN teams t2
ON m.away_team = t2.team_id;

关于mysql - sql join 返回两个相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54353442/

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