【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
相关推荐
知识分享小能手6 分钟前
MongoDB入门学习教程,从入门到精通,MongoDB副本集的核心机制(11)
数据库·学习·mongodb
一 乐9 分钟前
剧场管理系统|基于springboot + vue剧场管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·剧场管理系统
战族狼魂11 分钟前
AI 全程聊天式交互,自动修复错误--撸了一个中英多语言电商独立站,基于SpringBoot+React+MySQL 可Docker一键部署
spring boot·mysql·react.js
阿坤带你走近大数据13 分钟前
Oracle里的MINUS是什么
数据库·oracle
佩亚诺余项.15 分钟前
SQL Server 系统视图深度应用:批量检索含关键字的存储过程与数据表字段
数据库
小尔¥27 分钟前
MySQL故障排查与优化
运维·数据库·mysql
rrrjqy32 分钟前
Redis常见问题(一)
数据库·redis·缓存
Humbunklung33 分钟前
WMO 天气代码(Code Table 4677)深度解析与应用报告
开发语言·数据库·python
道清茗43 分钟前
【MySQL知识点问答题】锁机制、索引优化与数据库恢复方法
数据库·mysql
hero.fei1 小时前
排查redis出现报错ERR redis temporary failure
数据库·redis·缓存