需要一些帮助mysql内部连接

7rtdyuoh  于 2023-01-20  发布在  Mysql
关注(0)|答案(1)|浏览(126)

我有两个表,名为matchesteams

匹配:锦标赛ID、比赛ID、得分、主队ID和客场队ID enter image description here
小组:小组ID,小组名称enter image description here

我的SQL查询必须为home_team_id和away_team_id生成填充的team_name我知道我需要INNER JOIN来获得结果,但是我得到的唯一好的结果是home_team_id带有team_name或者away_team_id带有team_name,但不能同时使用这两个。

SELECT  matches.tournament_id,
    matches.match_id,
    matches.score,
    matches.home_team_id, 
    matches.away_team_id,
    teams.team_id,
    teams.team_name
FROM matches
INNER JOIN teams ON matches.home_team_id = teams.team_id
WHERE matches.tournament_id = 'WC-1930'

我怎样才能同时得到home_team_id和away_team_id的team_name的结果?

mzmfm0qo

mzmfm0qo1#

这是否有助于实现你想要的-添加第二个链接到球队的基础上客场队。编辑:有人指出,我的更改结束了一些重复的字段名称,所以我也修复了这个问题。

SELECT  matches.tournament_id,
    matches.match_id,
    matches.score,
    matches.home_team_id, 
    matches.away_team_id,
    h.team_id as home_id,
    h.team_name as home_name,
    a.team_id as away_id,
    a.team_name as away_name
FROM matches
INNER JOIN teams h ON matches.home_team_id = h.team_id
INNER JOIN teams a ON matches.away_team_id = a.team_id
WHERE matches.tournament_id = 'WC-1930'
ORDER BY matches.match_id ASC;

相关问题