Php 通过分组查找最大值
我有一个用户表:Php 通过分组查找最大值,php,mysql,group-by,having,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, 'c
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
)
我尝试过(没有成功):
如何修复我的请求?试试看
HAVING U.credits = MAX(U.credits)
仅仅拥有最高学分(美国学分)没有多大意义。这就像说有42个
-您没有将该值与任何值进行比较,因此所有行都将隐式匹配。尝试以下查询:
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)
或者“黑客”从中获取最多的连接信用证uid和剪切uid:
SELECT country,
substr(max(concat(lpad(credits,10,'0'),uid)),11) as uid,
max(credits) as credits
FROM users
group by country
最后一个示例通常是最快的,因为它发生在表上的一次传递中,没有子查询。此查询不起作用。在示例中,国家=2在结果中失败。由于您不能在未分组字段上使用“Having”,因此您无法使用简单的
groupby
查询(带或不带Having
)找到用户。您可以在子查询中使用它,也可以通过阅读找到快速正确解决方案的灵感。
SELECT *
FROM `users`
WHERE (country,credits)
IN (
SELECT country, max(credits)
FROM users
GROUP BY country
)
SELECT country,
substr(max(concat(lpad(credits,10,'0'),uid)),11) as uid,
max(credits) as credits
FROM users
group by country