如何select MySQL中一列的最大值的行?

How to select a row with maximum value for a column in MySQL?

*其他可用答案均未解决我的问题

我有一个table这样的

 id,cc,count
'1','HN','22'
'1','US','18'
'1','VN','1'
'2','DK','2'
'2','US','256'
'3','SK','1'
'3','US','66310'
'4','UA','2'
'4','US','263'
'6','FR','7'
'6','US','84'
'9','BR','3'

我想获取具有最大计数的 ID 的行,如下所示:

 id,cc,count
'1','HN','22'
'2','US','256'
'3','US','66310'
'4','US','263'
'6','US','84'
'9','BR','3'

我当前的代码是这样的,但我没有得到预期的结果:

SELECT t.* FROM  t
     JOIN (
       SELECT 
    t.id,t.cc
    ,max(t.count) as max_slash24_count
    FROM t 
    group by t.id,t.cc
      ) highest
     ON t.count = highest.max_slash24_count
  and t.cc = highest.cc

有人可以帮我吗?

group by 中删除 CC 列。试试这个。

SELECT t.* FROM  t
     JOIN (
       SELECT 
    t.id
    ,max(t.count) as max_slash24_count
    FROM t 
    group by t.id
      ) highest
     ON t.count = highest.max_slash24_count
  and t.id= highest.id

试试这个:

create table t (id varchar(10), cc varchar(10), count varchar(10))

insert into t (id,cc,count) values ('1','HN','22');
insert into t (id,cc,count) values ('1','US','18');
insert into t (id,cc,count) values ('1','VN','1');
insert into t (id,cc,count) values ('2','DK','2');
insert into t (id,cc,count) values ('2','US','256');
insert into t (id,cc,count) values ('3','SK','1');
insert into t (id,cc,count) values ('3','US','66310');
insert into t (id,cc,count) values ('4','UA','2');
insert into t (id,cc,count) values ('4','US','263');
insert into t (id,cc,count) values ('6','FR','7');
insert into t (id,cc,count) values ('6','US','84');
insert into t (id,cc,count) values ('9','BR','3');

select *
from t
where exists (
    select *
    from t as t1
    group by t1.id
    having t1.id = t.id and max(t1.count) = t.count
)

结果

ID  CC  COUNT
-------------
1   HN  22
2   US  256
3   US  66310
4   US  263
6   US  84
9   BR  3

勾选SQLFiddle

这个问题在 SO 上回答了很多次。查询就这么简单:

SELECT m.id, m.cc, m.count
FROM t m                         # "m" from "max"
    LEFT JOIN t b                # "b" from "bigger"
        ON m.id = b.id           # match a row in "m" with a row in "b" by `id`
        AND m.count < b.count    # match only rows from "b" having bigger count
WHERE b.count IS NULL            # there is no "bigger" count than "max"

您问题的真正问题在于列类型。如果 countchar(而不是 int),则字符串比较使用字典顺序而不是数字顺序进行。

例如,如果第三行显示为:

'1','VN','123'

您可能希望它在输出中被选中,因为 123 大于 22。这不会发生,因为作为字符串,'123' 小于 '22'.

即便如此,这已经得到解答,使用 SQL 中的 ROW_NUMBER 功能 服务器非常有趣:请查看此查询:

SELECT TT.Id, TT.cc, TT.count
FROM (
SELECT t.cc
  , t.count
  , @row_number:=CASE WHEN @Id=Id THEN @row_number+1 ELSE 1 END AS row_number
  , @Id:=Id AS Id
FROM t, (SELECT @row_number:=0, @Id:='') AS temp
ORDER BY t.Id, t.count DESC
    ) AS TT
WHERE TT.row_number = 1
ORDER BY TT.Id;

它产生预期的输出:

| Id | cc | count |
|----|----|-------|
|  1 | HN |    22 |
|  2 | US |   256 |
|  3 | US | 66310 |
|  4 | US |   263 |
|  6 | US |    84 |
|  9 | BR |     3 |

SQLFiddle

我从

获取了测试数据