我需要 MySQL 的 SQL 查询来选择关注者最多的前 10 人
我的桌子
编号 | 用户 ID | follow_id 1 3 6 2 3 7 3 4 6 4 5 6 5 7 3 6 9 7
从 id 为 6 的示例用户有 3 次跟随,7->2 和 3->1,所以 TOP 10 将是
用户 ID 为 6,7,3 ...
SELECT `follow_id`, COUNT(1) AS `followers`
FROM `tbl`
GROUP BY `follow_id`
ORDER BY COUNT(1) DESC
LIMIT 10;
您想使用 MySQL GROUP BY聚合功能
SELECT user_id, COUNT(follow_id) AS total_followers
FROM users
GROUP BY follow_id
ORDER BY total_followers LIMIT 10;
SELECT follow_id,count(id) AS cnt FROM table
GROUP BY follow_id ORDER BY cnt DESC LIMIT 10
您可以使用
SELECT user_id , COUNT(id) AS count FROM tbl GROUP BY follow_id ORDER BY count DESC LIMIT 10;
您需要按 follow_id 对结果进行分组,然后计算该组中有多少结果,并按每组的结果数以降序对其进行排序,然后定义您希望将其限制为仅 10 个结果,这可以通过使用 LIMIT 0,10
以下查询在 MySQL 5 中完美运行
SELECT follow_id, COUNT(follow_id) AS nr
FROM test.testtable
GROUP BY follow_id
ORDER BY nr DESC
LIMIT 0,10
尝试这样的事情:
select follow_id
from myTable
group by follow_id
order by count(user_id)
Limit 10
SELECT follow_id,
COUNT(user_id) AS number_of_followers
FROM table
GROUP BY follow_id
ORDER BY number_of_followers DESC
LIMIT 10;