2013-10-21 128 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)