Ruby on rails 如何改进查询以减少所花费的时间?
考虑到我有15个类别,每个类别有6个子类别,现在我有了items表,我必须根据最新购买日期从每个子类别中查找3个项目Ruby on rails 如何改进查询以减少所花费的时间?,ruby-on-rails,ruby-on-rails-3,query-optimization,Ruby On Rails,Ruby On Rails 3,Query Optimization,考虑到我有15个类别,每个类别有6个子类别,现在我有了items表,我必须根据最新购买日期从每个子类别中查找3个项目 category 1 ---> level 1 ---> 3 items with latest date category 1 ---> level 2 ---> 3 items with latest date ... ... ... category 15 ---> level 5 ---> 3 items with late
category 1 ---> level 1 ---> 3 items with latest date
category 1 ---> level 2 ---> 3 items with latest date
...
...
...
category 15 ---> level 5 ---> 3 items with latest date
category 15 ---> level 6 ---> 3 items with latest date
我试过了
@categories.each do |value|
@sub-categories.each do |value1|
array = Item.find(:all, :conditions => ["customer_id IN (?) AND category_id = ? AND sub-category_id = ?", @customer, value.id, value1.id], :order => 'created_at DESC', :limit => 3)
array.each do |value2|
@latest_item_of_each_customer << value2
end
end
end
@categories.each do| value|
@子类别。每个都有|值1|
数组=项.find(:all,:conditions=>[“客户id在(?)和类别id=?和子类别id=?”,@customer,value.id,value1.id],:order=>'created_at DESC',:limit=>3)
数组.每个do |值2|
@每个客户的最新\u项\u取决于您正在拉入的数据集的大小,加速嵌套循环的一种方法是急切地加载其中的一些关联
@categories = Category.all(:include => :sub_categories)
这将减少您正在进行的查询量,从而提高性能
如果你想阅读更多关于快速加载的内容,请看一看这篇文章。第一件事是。。。在item表中category_id的用途是什么,因为我们已经有sub_category_id,并且从sub_category中我们可以得到category,并且您需要每个子类别的项目
@latest_item_of_each_customer = []
@sub_categories = SubCategory.all
@sub_categories.each do |value1|
@latest_item_of_each_customer << Item.find(:all, :conditions => ["customer_id IN (?) and sub_category_id = ?", @customer, value1.id], :order => 'created_at DESC', :limit => 3)
end
@latest_item_of_each_customer = @latest_item_of_each_customer.flatten
@每个客户的最新商品=[]
@sub_categories=SubCategory.all
@子类别。每个不确定值1|
@每个客户的最新项目[“客户id在(?)和子类别中,@customer,value1.id],:order=>created\u at DESC',:limit=>3)
结束
@每个客户的最新项目=@latest\u item\u of\u每个客户的最新项目。展平
看看这篇文章: