sql 查询相互关注的人
现在有一张表为fans(粉丝表) 里面有两个字段from_user,to_user ,代表from_user关注了to_user
简单的写法sql,我也是这种写法😝
select
a.from_user,
a.to_user,
if(b.from_user is not null, 1, 0) as is_friend
from fans a left join fans b
on a.from_user = b.to_user and a.to_user = b.from_user
这个sql可以实现需求,问题是当用户量到了亿级别,关注关系到了百亿级别,join起来的效率就会很低。
借鉴了一篇博客😝
select
a.from_user,
a.to_user,
if( sum(1) over (partition by feature) > 1, 1, 0) as is_friend
from
(
select
a.from_user,
a.to_user,
if(from_user > to_user, concat(to_user, from_user), concat(from_user, to_user)) as feature
from fans
)
的确快上不少🤩🤩
借鉴博客:
计算互相关注的SQL应该怎么写
相关文章
怎么用SQL计算可能认识的人