我正在创建一个新表,需要根据用户帐户(超过几万个)的数据进行回填,使用以下一次性rake任务。
我决定为每2000个用户创建一个大的INSERT字符串,并执行该查询。
以下是代码的大致样子:
我决定为每2000个用户创建一个大的INSERT字符串,并执行该查询。
以下是代码的大致样子:
task :backfill_my_new_table => :environment do
inserts = []
User.find_each do |user|
tuple = # form the tuple based on user and user associations like (1, 'foo', 'bar', NULL)
inserts << tuple
end
# At this point, the inserts array is of size at least 20,000
conn = ActiveRecord::Base.connection
inserts.each_slice(2000) do |slice|
sql = "INSERT INTO my_new_table (ref_id, column_a, column_b, column_c) VALUES #{inserts.join(", ")}"
conn.execute(sql)
end
end
所以我在想,有没有更好的方法来做这个?我采取的方法有什么缺点?我应该如何改善它?如果我不切片 inserts
数组,而是简单地执行一个带有几十万个 VALUES 元组的单个 INSERT
,那么有什么缺点呢?
谢谢!