MySQL多个左联接-一栏不正确

时间:2019-06-06 22:48:20

标签: mysql

在我的MySQL数据库中,我有4个表:jtbl_userswat_teamwat_leaguewat_team_member。我需要运行一个查询,以提取一组团队成员的列表,以显示他们所在的团队以及该团队分配给的league_code。可以将一个团队成员分配给多个团队。

我无法将league_code与每个团队进行匹配,如果一个团队成员在多个团队中,则只会拉出该团队成员最近加入的league_code。< / p>

我必须从wat_team_member表中提取,该表不包含league_idleague_id' is in the wat_team`表。

`jtbl_users`
=============
id | name
1012 | James
1067 | Steve
1133 | Lisa

`wat_league`
=============
id | league_name | code
793 | Southeast County | x1234fr
678 | North County | df987gt

`wat_team`
=============
id | team_name | league_id | league_code
36 | Jawhawks | 793 | x1234fr
50 | Clippers | 678 | df987gt
62 | Bears | 793 | x1234fr

`wat_team_member`
=============
id | user_id | team_id
1 | 1012 | 36
2 | 1067 | 36
3 | 1067 | 50
4 | 1133 | 62

SELECT
jtbl_users.name,
wat_team.team_name,
wat_league.league_code
FROM wat_team_member

LEFT JOIN jtbl_users ON jtbl_users.id = wat_team_member.user_id
LEFT JOIN wat_team ON wat_team.id = wat_team_member.team_id
LEFT JOIN wat_league ON wat_league.id IN (SELECT league_id FROM wat_team WHERE wat_team_member.team_id = wat_team.id)
WHERE jtbl_users.id = 1067

返回:

name | team_name | league_code
--------------
Steve | Jawhawks | df987gt
Steve | Clippers | df987gt

但是需要:

name | team_name | league_code
--------------
Steve | Jawhawks | x1234fr
Steve | Clippers | df987gt

0 个答案:

没有答案