【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
相关推荐
月光晒了很凉快20 分钟前
数据库锁有哪些?什么是死锁?
数据库·mysql
灿彬垂死挣扎ing35 分钟前
PLSQL-将一份excel数据导入到一张物理表(Oracle)
数据库·oracle·excel
Hsu琛君珩42 分钟前
【Redis】Redis 典型应用 - 分布式锁原理与实现
数据库·redis·分布式
转瞬都有1 小时前
sqli-labs靶场自动化利用工具——第10关
python·sql·网络安全·自动化
微然02213 小时前
QT操作数据库
数据库
MonkeyKing_sunyuhua3 小时前
实现 Excel 文件导入到向量数据库(Milvus),并支持 先查询知识库(Milvus),然后再查询大模型(Ollama) 的功能
数据库·excel·milvus
往事随风吧@3 小时前
Oracle临时表
数据库·oracle
六百万~4 小时前
数据库MySQL
数据库·mysql
Czi橙4 小时前
SQL.LeetCode(1321)餐馆营业额变化增长
数据库·sql·mysql·leetcode
Feelings◎7 小时前
数据库——MySQL概述
数据库·mysql·oracle