gpt4 book ai didi

sql - "Popular"用户的 Rails 高效 SQL

转载 作者:数据小太阳 更新时间:2023-10-29 08:06:13 25 4
gpt4 key购买 nike

我正在用 Rails (3) 构建一个博客类型的网站,其中“作者”可以关注其他作者,并且为了找到拥有最多关注者的作者,我写了这个范围:

scope :popular, all.sort { |a, b| a.followers.count <=> b.followers.count }

我知道这真的很低效,因为它必须对数据库中的每个作者执行多个查询,然后比较结果。我问这个问题是为了看看是否有更好的方法来做到这一点。相关代码如下:

class Author < ActiveRecord::Base

has_many :relationships, :dependent => :destroy, :foreign_key => "follower_id"
has_many :following, :through => :relationships, :source => :followed
has_many :reverse_relationships, :dependent => :destroy, :foreign_key => "followed_id", :class_name => "Relationship"
has_many :followers, :through => :reverse_relationships, :source => :follower

scope :popular, all.sort { |a, b| a.followers.count <=> b.followers.count }

end

“追随者”是通过一个单独的模型实现的:

class Relationship < ActiveRecord::Base

belongs_to :follower, :class_name => "Author"
belongs_to :followed, :class_name => "Author"

end

以及检索流行作者:

@popular_authors = Author.popular[0..9]

我希望能够编写类似 Author.popular.limit(10) 的东西,但我知道为了让它工作,Author.popular 必须返回一个对象ActiveRecord::Relation 类,而不是数组。

正如我提到的,这段代码确实有效,但效率低得可怕,发出数百个查询只是为了找到排名前 10 位的作者。任何帮助将不胜感激!

最佳答案

一种优化可能是使用预先加载。我怀疑你有很多查询说,SELECT * fromAuthorWHEREfollower_id= 7

预加载可以将您的数百个查询变成一个巨大的查询。这可能会生成一个慢速查询,但通常会更快,因为慢速查询的时间少于 5000 次快速查询。

我不是 SQL 专家,但您可能还想使用 LIMIT = 10 的 GROUP_BY。获得最受欢迎的 10 个。

尝试类似的东西

Authors.find(:all, :include => Authors, :group_by => " SELECT `count` as (some subquery I don't know to get the number of followers)", :limit => 10)

Scroll down to Eager loading of associations

关于sql - "Popular"用户的 Rails 高效 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4527492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com