我正在做一个有很多用户的项目,一个用户有很多帖子。我正在尝试获取帖子数超过特定阈值的用户,但我使用的查询似乎不起作用。
User.where(id: user_ids)
.where(has_posts: true)
.joins(:posts)
.group('users.id')
.having('COUNT(posts.id) >= user.post_threshold')
然而,通过这个查询,我得到了 Unknown column posts.id in 'having clause':
任何有关如何解决此问题的帮助将不胜感激。
最佳答案
为此,您不需要 having
,一个简单的 where
就能很好地为您服务:
User.
where(id: user_ids).
where(has_posts: true).
where('COUNT(posts.id) >= users.post_threshold').
joins(:posts).
group('users.id')
编辑:在某些数据库上,您可能需要在选择中包含聚合,将此行添加到链中:
.select('*, COUNT(posts.id)')
关于mysql - 'having clause' : 中的未知列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42644969/