无法在一行中获取一个id和另一个同名id?

kiayqfof  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(348)

我不能让教练把运动员的名字排成一行

SELECT dev_test_team.team_id, dev_test_team.team_name,
dev_test_team.user_id, `dev_user`.`user_id` as `athlete_id`, 
`dev_user`.`user_type` FROM `dev_test_team`
CROSS JOIN `dev_user`
INNER JOIN `dev_test_teams_athlete` as `tt` ON `dev_user`.`user_id` = `tt`.`user_id` GROUP BY dev_test_team.team_id, dev_test_team.team_name, dev_test_team.user_id

这是对查询使用交叉连接关键字时的结果
我的dev\u test\u团队表是:

我的开发测试团队运动员表是:

我的dev\u user表是:

最后,我希望结果如表所示

----------------------------------------------------------------------------
 |first_name(coach_name)| first_name(athlete_name) | team_id  | team_name
 ---------------------------------------------------------------------------
        coach1                  athlete1                 1        ind
        coach2                  athlete2                 2        usa
        coach3                  athlete3                 3        uk
        coach3                  athlete4                 3        uk
2ledvvac

2ledvvac1#

你可以试着 JOINdev_user 两张table。
一个给 dev_test_teams_athlete table。
另一个给我 dev_test_team table。

CREATE TABLE dev_test_team(
   team_id int,
   team_name varchar(50),
   user_id int
);

insert into dev_test_team values (1,'indi',480);
insert into dev_test_team values (2,'usa', 472);
insert into dev_test_team values (3,'uk',  765);

CREATE TABLE dev_test_teams_athlete(
   teams_athlete_id int,
   team_id int,
   user_id int
);

insert into dev_test_teams_athlete values (12,1,380);
insert into dev_test_teams_athlete values (23,2,379);
insert into dev_test_teams_athlete values (24,3,479);
insert into dev_test_teams_athlete values (25,3,464);

CREATE TABLE dev_user(
   user_id int,
   first_name varchar(50)
);
insert into dev_user values (480,'coach1');
insert into dev_user values (472,'coach2');
insert into dev_user values (765,'coach3');
insert into dev_user values (380,'athlete1');
insert into dev_user values (379,'athlete2');
insert into dev_user values (479,'athlete3');
insert into dev_user values (464,'athlete4');

查询1:

SELECT coach.first_name 'first_name(coach_name)',
       athlete.first_name 'first_name(athlete_name)',
       dtt.team_id,
       dtt.team_name
FROM dev_test_team dtt 
INNER JOIN dev_test_teams_athlete  dtta on dtt.team_id = dtta.team_id
LEFT JOIN dev_user coach on dtt.user_id = coach.user_id
LEFT JOIN dev_user athlete on dtta.user_id = athlete.user_id

结果:

| first_name(coach_name) | first_name(athlete_name) | team_id | team_name |
|------------------------|--------------------------|---------|-----------|
|                 coach1 |                 athlete1 |       1 |      indi |
|                 coach2 |                 athlete2 |       2 |       usa |
|                 coach3 |                 athlete3 |       3 |        uk |
|                 coach3 |                 athlete4 |       3 |        uk |

相关问题