2013-05-22 81 views
0

考慮我有15個類別,每個類別有6個子類別,現在我有物品表,我必須根據最新購買日期從每個子類別中找到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 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 

這來回重複90次爲15categories X 6sub類,所以它會花費太多時間。請告訴我如何通過高效查詢來縮短時間。

+0

看看這篇文章:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql / – mccannf

回答

0

1)的第一件事是什麼...在項目表使用CATEGORY_ID的,因爲我們已經sub_category_id,和從sub_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