优化 ActiveRecord 查询
我一直在优化我的 Rails 应用程序,但我遇到了一个特定的查询:
def self.random_selection(n)
items = scoped(:joins => "JOIN (SELECT id
FROM #{table_name}
WHERE medias_count > 0
ORDER BY RAND()
LIMIT #{n.to_i}
) AS random_ids
ON #{table_name}.id = random_ids.id"
)
items.each do |genre|
genre.medias.sort! do |x,y|
y.vote_total <=> x.vote_total
end
end
items
end
这个想法是它将选择一些包含媒体的随机流派。一旦选择,它将对评价最高的媒体进行排序,我认为采用“顶级媒体”并在视图中使用它。
这是一个相当昂贵、丑陋的查询,我想要一些可以采取的方法来优化它。
我可以将媒体选择滚动到原始查询中吗?
我应该从另一个方向处理这个问题并选择随机的高评价媒体并从中获取流派吗? (也可以接受,但如果它没有提供任何改进,那么它们就没有意义)
我正在使用 Rails 3、Ruby 1.9.2 和带有 InnoDB 的 MySQL。
I've been working through optimising my Rails application but I'm stuck one particular query:
def self.random_selection(n)
items = scoped(:joins => "JOIN (SELECT id
FROM #{table_name}
WHERE medias_count > 0
ORDER BY RAND()
LIMIT #{n.to_i}
) AS random_ids
ON #{table_name}.id = random_ids.id"
)
items.each do |genre|
genre.medias.sort! do |x,y|
y.vote_total <=> x.vote_total
end
end
items
end
The idea is that it will select a number of random genres that have media within them. Once selected, it will then sort on the highest rated media, I think take that "top media" and use it within the view.
This is quite an expensive, ugly query and I'd like some approaches I could take on optimising it.
Could I roll the selection of medias into the original query?
Should I approach this from the other direction and select random high rated medias and fetch the genre from them? (also acceptable, but if it doesn't offer any improvement then theirs no point)
I'm using Rails 3, Ruby 1.9.2 and MySQL with InnoDB.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的解决方案
My solution