我有两个型号users
and posts
。用户可以投票和查看帖子
#users
id
name
#posts
id
count_votes
count_views
users_id
created_at
updated_at
我想要的是过去 24 小时内其帖子获得最多投票和浏览次数最多的用户。观看次数和得票数最多的获胜。
我尝试过的我有这个 SQL 查询,它很好,但我想让用户获得最大票数,这个查询给了我所有用户,但我不知道如何添加 count_views
select u.name as "Name", sum(p.count_votes)
from posts p
inner join users u on p.user_id = u.id
where p.created_at >= DATE_SUB(NOW(), INTERVAL 1 day)
group by user_id;
ActiveRecord 版本
Post.select("users.id, sum(posts.count_votes) as nb_votes")
.joins(:user).where("posts.created_at >= ?", 1.day.ago.beginning_of_day)
.group("posts.user_id")
# Results on IRB
=> #<ActiveRecord::Relation [#<Post id: 1>, #<Post id: 3>]>
如何将这两个和的总和和最大值结合起来?有没有办法拥有 activerecord 代码或只有原始 SQL ?
您当前的查询对用户进行分组。因此,您将在输出中为每个用户获得一条记录。通过将输出限制为仅 1 条记录并按投票数+浏览量总数排序,您可以获得排名靠前的用户。
Raw SQL:
select u.id, sum(p.count_votes + p.count_views) total
from posts p
inner join users u on p.user_id = u.id
where p.created_at >= DATE_SUB(NOW(), INTERVAL 1 day)
group by u.id
order by total DESC
limit 1 ;
ActiveRecord 版本:从您的 User 模型开始,因此您将在输出中获得用户对象而不是 Post 对象,就像您在问题中提到的那样。
User.select("users.id, sum(posts.count_votes + posts.count_views) as nb_votes")
.joins(:post).where("posts.created_at >= ?", 1.day.ago.beginning_of_day)
.group("posts.user_id").order("nb_votes DESC").limit(1)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)