Create table If Not Exists Relations (user_id int, follower_id int)
Truncate table Relations
insert into Relations (user_id, follower_id) values ('1', '3')
insert into Relations (user_id, follower_id) values ('2', '3')
insert into Relations (user_id, follower_id) values ('7', '3')
insert into Relations (user_id, follower_id) values ('1', '4')
insert into Relations (user_id, follower_id) values ('2', '4')
insert into Relations (user_id, follower_id) values ('7', '4')
insert into Relations (user_id, follower_id) values ('1', '5')
insert into Relations (user_id, follower_id) values ('2', '6')
insert into Relations (user_id, follower_id) values ('7', '5')
写出一个查询语句,找到具有最多共同关注者的所有两两结对组。换句话说,如果有两个用户的共同关注者是最大的,我们应该返回所有具有此最大值的两两结对组
结果返回表,每一行应该包含user1_id和 user2_id,其中user1_id < user2_id.
返回结果 不要求顺序 。
查询结果格式如下例:
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/all-the-pairs-with-the-maximum-number-of-common-followers
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
with table1 as(
select distinct
R1.user_id user1_id,
R2.user_id user2_id,
count(follower_id) num
from Relations R1
inner join Relations R2 using(follower_id)
where R1.user_id < R2.user_id
group by R1.user_id, R2.user_id
)
select
user1_id,
user2_id
from table1
where num = (select max(num) from table1)