簡體   English   中英

刪除 rails 中的數百萬條記錄

[英]deleting millions of records in rails

我們的 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 刪除一百萬條記錄,或者有沒有更好的方法來實現這一點。

您可以使用 TRUNCATE 而不是 DELETE。 TRUNCATE 刪除整個表並重新創建一個空表。 所以這要快得多。 TRUNCATE 還會重置表中 AUTO INCREMENT 字段的值

TRUNCATE TABLE yourTable;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM