首页 > 解决方案 > 没有公共字段时如何计算不同表中的数字?

问题描述

有一个 user 表和一个 user_follow 表,描述了哪些user.id正在关注/关注。我想计算该用户关注和被关注的次数。

问题是 user_follow 表没有 user_id 作为foreign key,所以我无法通过一个公共字段加入输入图像描述这两个表。我尝试使用LEFT OUTER JOINon user.id=user_follow.following_user_id and GROUP BY user.id,但它只计算关注的次数(关注的次数与以下完全相同,这是不对的)。

标签: mysqlsqloracle

解决方案


解决这个问题的方法是加入 USER_FOLLOW 两次,一次是 Followed By,一次是 Followed By。

您还没有发布 USER_FOLLOW 的结构,所以这是一个猜测,您需要更正它以适合您的架构。

select u.id, u.first_name, u.last_name
       , count(f.following_user_id) as following_count
       , count(fb.user_id) as followed_by_count
from user u
     left_outer join user_follow f on where f.user_id = u.id
     left_outer join user_follow fb on where fb.following_user_id = u.id
group by u.id, u.first_name, u.last_name

推荐阅读