# Write your MySQL query statement below
1729. 求关注者的数量
表: Followers
+-------------+------+ | Column Name | Type | +-------------+------+ | user_id | int | | follower_id | int | +-------------+------+ (user_id, follower_id) 是这个表的主键。 该表包含一个关注关系中关注者和用户的编号,其中关注者关注用户。
写出 SQL 语句,对于每一个用户,返回该用户的关注者数量。
按 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}
原站题解
pythondata 解法, 执行用时: 428 ms, 内存消耗: 59.7 MB, 提交时间: 2023-09-17 10:27:58
import pandas as pd def count_followers(followers: pd.DataFrame) -> pd.DataFrame: followers = followers.groupby('user_id',as_index=False).agg('count') followers = followers.rename(columns={'follower_id':'followers_count'}) return followers def count_followers2(followers: pd.DataFrame) -> pd.DataFrame: followers.columns=['user_id','followers_count'] return followers.groupby('user_id')['followers_count'].count().reset_index()
mysql 解法, 执行用时: 587 ms, 内存消耗: 0 B, 提交时间: 2022-06-06 10:22:02
# Write your MySQL query statement below select user_id, count(follower_id) as followers_count from followers group by user_id order by user_id asc;
mysql 解法, 执行用时: 295 ms, 内存消耗: 0 B, 提交时间: 2022-05-27 11:09:12
# Write your MySQL query statement below select user_id, count(follower_id) as followers_count from followers group by user_id order by user_id asc;