mysql 特定查询

标签 mysql sql

我有两个表:teamsformations :

团队:

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/

相关文章:

sql - 快速 SQL 问题 : Correct syntax for creating a table with a primary key in H2?

mysql - 在给定时间范围内按小时分组

php - 带有两个where子句的mysql查询

mysql - 根据其他行值从 SQL 表查询数据

javascript - 使用 Ajax 和 Jquery 发送数据

php - 这是 MYSQL 或 PHP 错误吗?当mysql_fetch_array

sql - 没有交叉连接的未售出产品查询?

sql - 在sql中的某些单词之间选择数字

c# - Mysql和c#更新

php - 如何在不同时间将2条记录存储在同一列上?