2013-10-02 75 views
2

使用Rails 3.2,Ruby 1.9,will_paginate。我有10萬條記錄,並測試了以下疑問:Rails排序或訂購查詢很慢

# 1000+ms to load 
@shops = Shop.where(:shop_type => @type).paginate(:include => :photos, :page => params[:page], :per_page => 25, :order => 'created_at DESC') 

# 1000+ms to load 
@shops = Shop.paginate(:include => :photos, :page => params[:page], :per_page => 25, :order => 'created_at DESC') 

# 1000+ms to load 
@shops = Shop.order('created_at DESC').limit(25) 

# 1+ms to load 
@shops = Shop.paginate(:include => :photos, :page => params[:page], :per_page => 25) 

我注意到order選項是慢得令人難以置信。測試結果顯示will_paginate不是問題。

我該如何更改它,以便可以加快order的查詢速度。

+1

在訂單欄添加索引? – apneadiving

+0

@apneadiving想到這一點。任何可以排序/排序的東西都必須編入索引? – Victor

+1

只有當你想快速。相對而言,索引相當便宜。 – railsdog

回答

3

是的,嘗試在訂單欄上創建索引。它會加快速度。