mysql - 没有公共字段时如何计算不同表中的数字?
问题描述
有一个 user 表和一个 user_follow 表,描述了哪些user.id
正在关注/关注。我想计算该用户关注和被关注的次数。
问题是 user_follow 表没有 user_id 作为foreign key
,所以我无法通过一个公共字段加入输入图像描述这两个表。我尝试使用LEFT OUTER JOIN
on user.id=user_follow.following_user_id and GROUP BY user.id
,但它只计算关注的次数(关注的次数与以下完全相同,这是不对的)。
解决方案
解决这个问题的方法是加入 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
推荐阅读
- r - 如何比较两个 data.frames 并删除 R 中特定两列中的相同条目?
- node.js - Discord.js 应用系统?
- java - 电影 IMDb 前 250 个分类器代码 - 使用 *.get(
); - npm - npm pack / publish:找不到文件
- excel - Excel VBA:单击单元格时确定鼠标位置
- c# - 未找到视图组件
- postgresql - 获取调用某个函数的所有触发器
- json - Spark json 模式验证
- java - 休眠序列生成器,ConstraintViolationException
- javascript - 检查用户是否在页面底部不适用于移动设备