【问题标题】:deleting millions of records in rails删除 Rails 中的数百万条记录
【发布时间】:2016-05-25 09:49:57
【问题描述】:

我们的 RoR 4 应用有数百万条记录,需要定期删除。目前删除是作为后台作业发生的:

 while fruit.apples.count > 0
      # create the sql query to delete 1000 feeds from the channel
      sql = "DELETE FROM apples WHERE fruit_id=#{fruit_id} LIMIT 1000"
      # execute the sql query
      ActiveRecord::Base.connection.execute(sql)
      # wait a bit before the next delete
      sleep 0.1
 end

因为我每隔几秒就进行一次计数,所以它已经使 mysql 服务器的 cpu 时间达到峰值。所以想知道我是否可以使用 delete_all/destroy_all 删除一百万条记录,或者有没有更好的方法来实现这一点。

【问题讨论】:

标签: mysql ruby-on-rails-4


【解决方案1】:

您可以使用 TRUNCATE 代替 DELETE。 TRUNCATE 删除整个表并重新创建一个空表。所以这要快得多。 TRUNCATE 还会重置表中 AUTO INCREMENT 字段的值

TRUNCATE TABLE yourTable;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2016-03-06
    • 2016-09-05
    相关资源
    最近更新 更多