通过大量SQL调用加速慢速功能

时间:2012-07-05 18:17:01

标签: mysql ruby-on-rails ruby

我需要生成一个报告,该报告返回给定时间范围内的一组数字。

例如,我需要返回给定月份观看的分钟数。这就是我现在运行的内容

presentation = Presentation.find(1)
presentation.video.stats.minutes_by_date(Date.new(2012,6,1),Date.new(2012,6,30))


def self.by_date(start_date,end_date)
    vals = Array.new
    (start_date..end_date).map { |date|
      yesterdays_stat = daily_watched(date.yesterday)
      todays_stat = daily_watched(date)

      if todays_stat > 0
        if yesterdays_stat > 0
          difference = todays_stat - yesterdays_stat
        else
          difference = todays_stat
        end
        watched_in_meg = (difference / 1024).round(2)
        vals.push (watched_in_meg / first.video.meg_per_minute).round(2)
      else
        vals.push 0
      end
    }
    vals
  end

  def self.daily_watched(date)
    # get the total bytes for the from both flash and mp4
    total_bytes = 0
    bytes = where(["DATE(generated_date) = ?", date]).group("kbytes")
    .order('generated_date')
    bytes.each do |byte|
      total_bytes += byte.kbytes
    end
    total_bytes
    # Get the bytes of both flash and mp4
  end

输出需要如下所示:

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 54.09, 0]

问题是每次演示必须运行30次,我有10到500个演示文稿。

有没有办法提高效率?

2 个答案:

答案 0 :(得分:1)

您可以首先使用单个查询获取所有日期的统计信息,然后通过数组一次传递来计算差异。

查询看起来大致如下:

result = Thing.select("DATE(generated_date) as date, SUM(kbytes) as sum_kbytes").group("DATE(generated_date)").where...
result.each{|i| puts "#{i.date} #{i.sum_kbytes}"}

答案 1 :(得分:0)

预先计算每天每个演示文稿的差异var。然后从此函数中的预先计算的表中读取。