2013-10-21 131 views
0

我的網頁有問題。緩慢的SQL查詢

它的運行速度非常慢,所以我在互聯網上讀到它可能是SQL的一個糟糕用法。所以我評論了更復雜的SQL行,並且它再次順利運行。

我的問題是:'有沒有辦法讓這個SQL請求「更輕」?

@companies = Company.where('tbl_companys.state = "enabled"') 

    @companies = @companies.includes(:benefit).where("tbl_benefits.end_date >= {Date.today}") 

    @companies = @companies.includes(:benefit).where(tbl_benefits: { state: 'enabled' }) 

    has_benef_gastro = false 

    has_benef_hote = false 

    has_benef_ent = false 

    until has_benef_gastro == true 

     @esta_gastro = (@companies.where('id_category = "2-gastronomia"').shuffle)[0] 

     @benefit_gastro = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', @esta_gastro.id_company, Date.today).first 

     if @benefit_gastro.nil? == false 

      has_benef_gastro = true 

     end 

    end 

    until has_benef_hote == true 

     @esta_hotelero = (@companies.where('id_category = "1-hoteleria"').shuffle)[0] 

     @benefit_hote = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', @esta_hotelero.id_company, Date.today).first 

     if @benefit_hote.nil? == false 

      has_benef_gastro = true 

     end 

    end 

    until has_benef_ent == true 

     @esta_ent = (@companies.where('id_category = "3-entretenimiento"').shuffle)[0] 

     @benefit_ent = Benefit.where('id_company = ? AND end_date >= ? AND state = "enabled"', @esta_ent.id_company, Date.today).first 

     if @benefit_ent.nil? == false 

      has_benef_gastro = true 

     end 

    end 

感謝您的幫助!

+0

要做的第一件事是在每行之間輸出timediffs以查看時間到了哪裏。如果您最終希望調整SQL,則需要提供表定義,卷和索引。 – Laurence

+0

洗牌的使用與我有關。基本上,在我看來,你會得到一個隨機公司,檢查是否有效,如果不重複。是對的嗎? –

回答

0

最後我做一個簡單的SQL請求,所以我並沒有與一些軌道的問題作鬥爭。

無論如何,謝謝!

0

您每次都在洗牌@esta_gastro@esta_hotelero,@esta_ent@benefit_變量,這沒有任何意義。每做一次循環就需要多次新的數據庫查詢。

如果你想找到一個隨機選擇,只需在循環外創建你的集合,一次(在循環之外)洗牌,然後遍歷這些集合,直到你滿足你的標準。

例如:

@esta_gastro = @companies.where('id_category = "2-gastronomia"').shuffle 
@benefits = Benefit.where('end_date >= ? AND state = "enabled"', Date.today) 
@benefit_gastro = nil 
i = 0 
until [email protected]_gastro.blank? 
    @benefit_gastro = @benefits.where('id_company = ?', @esta_gastro[i].id_company).first 
    i += 1 
end 

編輯

如果整個目標是讓@benefit_gastro定義,那麼我甚至不認爲你需要一個循環。您可以定義@esta_gastro集合,然後使用它找到所有對應的優點。由於@esta_gastro被打亂,你@benefit_gastro將是隨機的:

@esta_gastro = @companies.where('id_category = "2-gastronomia"').shuffle 
@benefit_gastro = Benefit.where('end_date >= ? AND state = "enabled"', Date.today).where('id_company = ?', @esta_gastro.map(&:id)).limit(1)