考慮我有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類,所以它會花費太多時間。請告訴我如何通過高效查詢來縮短時間。
看看這篇文章:http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql / – mccannf