【SQL】关注者数量

目录

题目

分析

代码


题目

表: Followers

复制代码
+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id     | int  |
| follower_id | int  |
+-------------+------+
(user_id, follower_id) 是这个表的主键(具有唯一值的列的组合)。
该表包含一个关注关系中关注者和用户的编号,其中关注者关注用户。

编写解决方案,对于每一个用户,返回该用户的关注者数量。

user_id 的顺序返回结果表。

查询结果的格式如下示例所示。

示例 1:

复制代码
输入:
Followers 表:
+---------+-------------+
| user_id | follower_id |
+---------+-------------+
| 0       | 1           |
| 1       | 0           |
| 2       | 0           |
| 2       | 1           |
+---------+-------------+
输出:
+---------+----------------+
| user_id | followers_count|
+---------+----------------+
| 0       | 1              |
| 1       | 1              |
| 2       | 2              |
+---------+----------------+
解释:
0 的关注者有 {1}
1 的关注者有 {0}
2 的关注者有 {0,1}

分析

于每一个用户

按照用户id分组,group by user_id

返回该用户的关注者数量

count计数,count(follower_id) followers_count

按 user_id 的顺序返回结果表。

使用order by升序排列order by user_id

代码

复制代码
select user_id, count(follower_id) followers_count
from Followers
group by user_id
order by user_id
相关推荐
GreatSQL2 小时前
MySQL迁移至GreatSQL后,timestamp字段插入报错解析
数据库
粘豆煮包3 小时前
掀起你的盖头来之《数据库揭秘》-3-SQL 核心技能速成笔记-查询、过滤、排序、分组等
后端·mysql
expect7g3 小时前
COW、MOR、MOW
大数据·数据库·后端
DemonAvenger4 小时前
MySQL海量数据快速导入导出技巧:从实战到优化
数据库·mysql·性能优化
程序新视界16 小时前
MySQL中什么是回表查询,如何避免和优化?
mysql
薛定谔的算法21 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
Databend1 天前
Databend 亮相 RustChinaConf 2025,分享基于 Rust 构建商业化数仓平台的探索
数据库
得物技术1 天前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
Java水解1 天前
【MySQL】从零开始学习MySQL:基础与安装指南
后端·mysql
Raymond运维1 天前
MariaDB源码编译安装(二)
运维·数据库·mariadb