通过分组查找最大值

I have a users table:

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

I want to find users with max credits grouped by country. Example output:

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

I have tried (not successful):

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

How can I fix my request?

Try this query:

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)

Try

HAVING U.credits = MAX(U.credits)

Just HAVING MAX(u.credits) doesn't make much sense. That'd be like saying HAVING 42 - you're not comparing that value to anything, so ALL rows will be implicitly matched.

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

Test on sqlfiddle.com

Or "hack" with get maximum of concatenated credits-uid and cut uid from it:

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

The last example is usually the fastest, because it takes place in a single pass on a table, without subqueries.