通过分组查找最大值

时间:2016-08-31 21:26:12

标签: php mysql group-by having

我有一个用户表:

uid country credits
1  1      10
2  1      8
3  2      4
4  2      6

我想找到按国家/地区分组的最高分的用户。 示例输出:

[0] => Array(
  'country' => 1,
  'uid'     => 1,
  'credits' => 10
),
[1] => Array(
  'country' => 2,
  'uid'     => 4,
  'credits' => 6
)

我尝试过(不成功):

SELECT 
   U.*
FROM 
   `users` AS U
WHERE
   U.user_deleted = 0
GROUP BY
   U.country
HAVING
   MAX(U.credits)

如何修复我的请求?

3 个答案:

答案 0 :(得分:1)

尝试

HAVING U.credits = MAX(U.credits)

只是HAVING MAX(u.credits)没有多大意义。这就像说HAVING 42 - 您没有将该值与任何内容进行比较,因此所有行都将被隐式匹配。

答案 1 :(得分:1)

尝试此查询:

SELECT 
   u.*
FROM 
   `users` AS u
WHERE
   u.credits = (select max(u1.credits) from users u1 where u1.country=u.country  group by u1.country)

答案 2 :(得分:1)

SELECT *
  FROM `users`
 WHERE (country,credits)
    IN (
        SELECT country, max(credits)
          FROM users
         GROUP BY country
       )

Test on sqlfiddle.com

或者“黑客”获得最多的联合信用 - 并且从中削减了uid:

SELECT country, 
       substr(max(concat(lpad(credits,10,'0'),uid)),11) as uid,
       max(credits) as credits
  FROM users
 group by country

Test on sqlfiddle.com

最后一个例子通常是最快的,因为它只在一个表上传递,没有子查询。