当前位置: 首页> 文旅> 旅游 > 【SQL】关注者数量

【SQL】关注者数量

时间:2025/7/9 6:11:49来源:https://blog.csdn.net/weixin_73404807/article/details/141334926 浏览次数:0次

目录

题目

分析

代码


题目

表: 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

关键字:【SQL】关注者数量

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: