我正在尝试选择具有MAX微博计数的用户:
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*)
,但这不起作用。
答案 0 :(得分:9)
我尝试使用ORDER BY max DESC LIMIT 1,其中maximum是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可用,所以我在纸上做这个(它可能不起作用),但它只是一个方向。
答案 1 :(得分:2)
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
答案 2 :(得分: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)
没有测试,但它可能有效
答案 3 :(得分: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
答案 4 :(得分:0)
这很简单,你可以尝试:
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