8

我正在尝试选择拥有 MAX microposts 计数的用户:

SELECT "name", count(*) FROM "users" 
  INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
  GROUP BY users.id

这会返回

"Delphia Gleichner";15
"Louvenia Bednar IV";10
"Example User";53
"Guadalupe Volkman";20
"Isabella Harvey";30
"Madeline Franecki II";40

但我只想选择"Example User";53,(拥有 MAX 微博数的用户)

我试图添加HAVING MAX(count*),但这没有用。

4

5 回答 5

15

我会尝试使用 ORDER BY max DESC LIMIT 1,其中最大值是 count(*) 字段。就像是:

SELECT "name", count(*) maximum FROM "users" 
   INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
GROUP BY users.id 
ORDER BY maximum DESC 
LIMIT 1

我现在没有可用的 mysql,所以我在纸上做这个(它可能不起作用),但这只是一个方向。

于 2013-09-30T07:53:39.413 回答
4
SELECT x.name, MAX(x.count)
FROM (
 SELECT "name", count(*)
  FROM "users" INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
  GROUP BY users.id
) x
GROUP BY x.name
于 2013-09-30T07:54:29.090 回答
1

很简单,你可以试试:

SELECT "name", MAX(count_num) FROM 
(SELECT "name", count(*) as count_num
FROM "users" INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id"
GROUP BY users.id) x
于 2018-01-26T23:21:44.953 回答
0

也许是这样的:

SELECT "name", count(*) 
FROM "users" 
INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
GROUP BY users.id
HAVING COUNT(microposts) = (SELECT COUNT(microposts) 
                         FROM   users
                         GROUP  BY microposts
                         ORDER  BY COUNT(microposts) DESC 
                         LIMIT  1) 

没测试过,不过应该可以

于 2013-09-30T07:53:38.347 回答
0
SELECT TOP 1 "name", count(*) AS ItemCount FROM "users" 
INNER JOIN "microposts" ON "microposts"."user_id" = "users"."id" 
GROUP BY users.id
ORDER BY ItemCount DESC
于 2013-09-30T07:53:56.397 回答