0

ウェブページに問題があります。

実行速度が非常に遅かったため、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

ご協力いただきありがとうございます !

4

2 に答える 2

0

@esta_gastro@esta_hotelero@esta_ent、および@benefit_変数を毎回シャッフルしていますが、これはあまり意味がありません。ループを実行するたびに、複数の新しい DB クエリが必要になります。

ランダムな選択を見つけたい場合は、ループの外側でセットを作成し、(ループの外側で) 1 回シャッフルしてから、基準を満たすまでそれらのセットを繰り返します。

例えば:

@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 !@benefit_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)
于 2013-10-21T23:05:31.430 に答える