【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
相关推荐
heze092 小时前
sqli-labs-Less-18自动化注入方法
mysql·网络安全·自动化
木风小助理2 小时前
PostgreSQL基础知识——DDL深度解析
数据库·postgresql
hanqunfeng2 小时前
(四十四)Redis8 新增的数据类型 -- Vector Set
数据库·redis·缓存
梦梦代码精3 小时前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
纪莫5 小时前
技术面:MySQL篇(InnoDB的锁机制)
java·数据库·java面试⑧股
Filotimo_5 小时前
在java开发中,cron表达式概念
java·开发语言·数据库
DBA小马哥6 小时前
从MongoDB迁移到金仓数据库:数据模型与业务连续性难题的保姆级指南
数据库·mongodb·dba
QZ166560951596 小时前
低误差率、高性能、符合审计要求的金融数据库审计和监测最佳实践指南
数据库·金融
愚公移码6 小时前
蓝凌EKP产品:主文档权限机制浅析
java·前端·数据库·蓝凌
此生只爱蛋6 小时前
【Redis】持久化
数据库·redis