mysql - SQL从数据库中选择具有最大值的行并按2列分组

标签 mysql sql database max left-join

<分区>

我有这张表:

TABLE 优惠

 +------+--------------+----------+----------------+
 | id   | player_id    | team_id  | valore         |
 +------+--------------+----------+----------------+
 | 1    | 1            | 1        | 230            |
 | 2    | 1            | 3        | 150            |
 | 3    | 9            | 3        | 150            |
 | 4    | 1            | 5        | 100            |
 | 5    | 7            | 5        | 37             |
 | 6    | 7            | 1        | 38             |
 +------+--------------+----------+----------------+

我期待这样的结果, 我想创建一个这样的 View :

+------+--------------+----------+----------------+
| id   | player_id    | team_id  | valore         |
+------+--------------+----------+----------------+
| 1    | 1            | 1        | 230            |
| 3    | 9            | 3        | 150            |
| 6    | 7            | 1        | 38             |
+------+--------------+----------+----------------+

我尝试使用此 SQL 代码:

创建 View ...

select t1.* 
  from offers t1
       left join ( select player_id, 
                          team_id, 
                          max(valore) as valore
                     from offers
                 group by player_id, 
                          team_id) t2 
                 on t1.player_id = t2.player_id 
                    and t1.team_id = t2.team_id 
                    and t1.valore = t2.valore

但结果与第一个表相同......它没有改变任何东西。 谁能帮帮我?

最佳答案

您的预期结果并未在GROUP BY 子句中建议team_id,它实际上是基于player_id。因此,将其从 GROUP BY 子句中删除并将 ON 子句更改为 t1.player_id = t2.player_id and t1.valore = t2.valore

因此,您的查询将是:

create view...
    select t1.*  
    from offers t1 inner join 
        (select player_id, max(valore) as valore
         from offers
         group by player_id
        ) t2 
       on t1.player_id = t2.player_id and
          t1.valore = t2.valore;

但是,我会这样做:

create view v1 as
    select o.*
    from offers o
    where valore = (select max(o1.valore)
                    from offer o1
                    where o1.player_id = o.player_id
                   );

关于mysql - SQL从数据库中选择具有最大值的行并按2列分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52056551/

相关文章:

MySQL:为什么是 varchar(254) 而不是 varchar(255)?

sql - 使用 SQL 对重复的 0 和 1 系列中的中断进行识别和分类

php - 几个查询mysqli

mysql - 如何从 mysql 数据库中的 3 个表中检索值?

MYSQL 整理性能

MySQL 查询选择不同字段然后按日期排序

mysql - SQL 连接多次?

java - 通过 JDBC 连接到数据库

mysql - 有没有办法在 SQL 中仅向 1 行添加属性?

MySQL 使用 IN 子句和子查询进行更新