mysql - 仅选择具有其他唯一列的特定记录的最高值?

标签 mysql sql group-by max

我有一个表,其中包含类似于以下的数据。我需要的查询将导致具有最高 cityID 值的 Orange 和 Apple 的最佳结果。

id | fruit  | attr | cityID | personID 
163 Apple   green   3685    235
163 Apple   red     3145    267
163 Apple   yellow  1522    560
164 Orange  big     1344    147
164 Orange  small   833     2673

我需要的结果是

id | fruit  | attr | cityID | personID 
163 Apple   green   3685    235
164 Orange  big     1344    147

我开始尝试用

来完成这个
select 
   fruit_id,
   fruit,
   attr, 
   max(cityID),
   personID
from fruits_cities
    group by
     fruit_id,
     fruit,
     attr, 
     max(cityID),
     personID

最佳答案

这是一个挑战。您需要使用某种比较。这是一个简单的方法:

select fc.* 
from fruits_cities fc
where fc.cityId = (select max(CityId)
                   from fruits_cities fc2
                   where fc2.fruit_id = fc.fruit_id
                  );

关于mysql - 仅选择具有其他唯一列的特定记录的最高值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803954/

相关文章:

mysql - 将 Rollup 与子查询结合使用

php - MySQL STR_TO_DATE() 返回无效日期

sql - SQL Server 如何处理非聚集索引中的包含列?

c# - Linq GroupBy 将每个空值作为一个组

MySQL 对最后一个进行排序和分组

mysql - 是否可以在 MySQL 表上执行内联 GROUP BY?

用于存储负数的 MySQL 数据类型

javascript - 选中复选框时在php中调用js函数

sql - 计算sql查询中的持续时间总和

mysql - 为什么sql order by 很慢?