【问题标题】:Rails - Active record querying with 350,000 records takes too much timeRails - 使用 350,000 条记录查询活动记录需要太多时间
【发布时间】:2017-07-11 09:15:15
【问题描述】:

我正在尝试根据日期和发送该特定消息的数量绘制图表。获取此计数的查询通过下面提到的三个表运行。

帐户表、消息表和关键字表

联想是这样的。

  • 关键字 has_many 帐户。
  • 帐户 has_many Messages 和 belongs_to 关键字
  • 消息属于帐户

我需要查看每天发送的消息数量。

这是我正在使用的查询。

(@from_date.to_date..@to_date.to_date).map {|date|
Message.joins(:account).where("date(messages.created_at) = ? 
AND accounts.keyword_id = ?", date, keyword.id).count.to_f}.inspect

如果有任何建议可以减少运行此查询的时间,请告诉我。

【问题讨论】:

    标签: sql ruby-on-rails activerecord postgresql-9.1 psql


    【解决方案1】:

    我认为你可以这样做:

    keyword.messages.where(
        :created_at => [@from_date.to_date..@to_date.to_date]
    ).count
    

    它会这样查询:

    SELECT COUNT(*)
    FROM `messages`
    WHERE `keyword_id` = [keyword.id] AND (`created_at` BETWEEN '[from_date]' AND '[to_date]')
    

    【讨论】:

      【解决方案2】:

      在Message模型里面添加这个

      def date
        self.created_at.strftime('"%d-%m-%Y')
      end
      
       Message.joins(:account).where("date(messages.created_at) <= ?  AND date(messages.created_at) >= ? AND accounts.keyword_id = ?", @from_date.to_date,@to_date.to_date, keyword.id).group(:date).count
      

      试试上面的方法可以帮到你

      【讨论】:

        猜你喜欢
        • 2015-12-12
        • 2016-08-05
        • 2013-02-01
        • 1970-01-01
        • 2012-04-18
        • 2016-07-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多