有2个表:
users: id, name
albums: id, user_id
我需要一个SQL查询,该查询查找相册数量最多的用户的姓名。我怎么做?
这是我到目前为止尝试过的-
SELECT Users.name
FROM Users
JOIN Albums
ON Users.id = Albums.user_id
HAVING COUNT(Albums.id) = MAX(COUNT(Albums.id));
(这不起作用)
答案 0 :(得分:1)
您可以使用限制1
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noEmitHelpers": true,
"sourceMap": false,
"baseUrl": "./src",
"paths": {}
},
"exclude": [
"node_modules"
]
}
import ViewBase from "core/view/ViewBase";
import { BLACK_TYPE, CLICK_TYPE } from "core/view/BlackBG";
import { UIPANEL } from "core/view/UIRoot";
import MessageBox from "core/view/notify/MessageBox";
或过滤器,使beas在max上获得最大计数
select Users.name, count(distinct Albums.id) max_count
from Users
INNER JOIN Albums on Users.id = Albums.user_id
GROUP BY Users.name
ORDER max_count desc limit 1
答案 1 :(得分:1)
我只会使用join
,group by
和limit
:
SELECT u.name
FROM Users u JOIN
Albums a
ON u.id = a.user_id
GROUP BY u.name
ORDER BY COUNT(*) DESC
LIMIT 1;
这有一些假设:
u.id
中加入GROUP BY
。答案 2 :(得分:0)
此子查询应返回相册数量最大的用户的名称。
SELECT name FROM Users WHERE id = (SELECT user_id FROM Albums GROUP BY user_id ORDER BY COUNT(*) DESC LIMIT 1);
这里是GROUP BY,用于将user_id与出现的每个user_id的COUNT进行分组,否则返回表中所有记录的计数。
如果出现多个具有相同计数的最大出现次数,则必须使用IN关键字进行查询以返回所有名称,并且查询会有点复杂。