【问题标题】:Rail's ActiveRecord find_each with DISTINCT selectRail 的 ActiveRecord find_each 与 DISTINCT 选择
【发布时间】:2015-12-22 20:18:34
【问题描述】:

我想获取数据库中所有唯一电子邮件的列表,并使用find_each 批量处理它们。

下面的代码可以正常工作,直到它有超过 1000 条记录(批量大小)要处理。然后它在第 1000 条记录后中断并显示错误消息Primary key not included in the custom select clause

Tourist.select('DISTINCT email').where("DATE(created_at) = ?", Date.today-  1).find_in_batches do |group|
    something
end

那么,我该如何链接所有这些:

  • 我只需要一个特定的字段(电子邮件)
  • 我需要它们是独一无二的
  • 我需要一个 where 子句
  • 我需要一个 find_each

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    您必须使用循环手动完成 limitoffset

    batch_size = 1000
    offset = 0
    
    loop do
      emails = Tourist.where("DATE(created_at) = ?", Date.today-1).select('DISTINCT email').limit(batch_size).offset(offset)
      emails.each do |email| 
        # your stuff
      end 
    
      break if emails.size < batch_size
      offset += batch_size
    end
    

    当然,只有在请求将检索大量电子邮件时才需要这样做。否则只需使用Tourist.where(condition).pluck('DISTINCT email').each { |email| your stuff }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-01
      • 2013-08-17
      相关资源
      最近更新 更多