我有两个表:teams
和 formations
:
表团队:
team_id | team_name
1 | Barcelona
2 | Real Madrid
3 | PSG
表格构成:
formation_id | team_id | module
1 | 2 | 5-3-2
2 | 1 | 4-4-2
3 | 3 | 4-4-2
4 | 2 | 4-4-3
实际上,我需要在 2 个表 GROUP BY team_id 之间进行“连接”,但需要使用最后一个“formation_id”
结果是这样的:
team_id | team_name | formation_id | module
1 | Barcelona | 2 | 4-4-2
2 | Real Madrid| 4 | 4-4-3
3 | PSG | 3 | 4-4-2
实际上我的查询是:
SELECT *
FROM formations f
INNER JOIN teams t
ON (f.team_id = t.team_id)
GROUP BY t.team_id
通过查询,我为每个团队选择了第一个插入阵型,而我必须为每个团队选择最后一个阵型。
最佳答案
检查这个 SQLFIDDLE
SELECT A.team_id,A.team_name,B.formation_id,B.module
FROM teams A,formations B
WHERE A.team_id=B.team_id
AND B.formation_id =
(
SELECT max(formation_id)
FROM formations C
WHERE C.team_id =B.team_id
)
ORDER BY A.team_id;
create table teams
(
team_id int
,team_name varchar(40)
);
create table formations
(
formation_id int
,team_id int
,module int
);
insert into teams
values
(1,'Barcelona'),(2,'Real Madrid'),(3,'PSG');
insert into formations
values
(1,2,532),(2,1,442),(3,3,442),(4,2,443);
关于mysql 特定查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12500905/