gpt4 book ai didi

mysql - 事件记录 : Delete duplicate records

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:14 26 4
gpt4 key购买 nike

如果在特定日期有多个记录,我想删除当天除最新记录外的所有记录。例如,在下表中,id 为 9、10、12 的记录具有相同的日期。因此,应删除 9 和 10,因为 ID 为 12 的记录具有最新日期。

id      date
1 2012-04-25 00:00:00.000000
2 2012-04-26 00:00:00.000000
3 2012-04-23 00:00:00.000000
4 2012-04-24 00:00:00.000000
5 2012-05-01 00:00:00.000000
6 2012-05-02 00:00:00.000000
7 2012-05-03 00:00:00.000000
8 2012-05-04 00:00:00.000000
9 2012-04-30 00:30:00.000000
10 2012-04-30 18:00:00.000000
11 2012-04-29 00:00:00.000000
12 2012-04-30 18:40:00.000000
13 2012-05-05 00:00:00.000000
14 2012-05-05 09:31:31.000000

这是删除重复项的(脏)rake 任务

task :remove_duplicate do
Rake::Task["remove_duplicate"].invoke
end

task :remove_duplicate => :environment do
weights = Weight.count(:group => "DATE(date)", :having => "COUNT(id) > 1")
weights_to_delete = []
weights.each do |weight|

start_date = weight[0].to_date.beginning_of_day
end_date = weight[0].to_date.end_of_day
day_weights = Weight.where("date >= ? and date <= ?", start_date, end_date).order(:date)
day_weights[0..-2].each do |weight|
weights_to_delete.push weight.id
end
end
Weight.delete(weights_to_delete)
end

虽然我能够按照我解释的那样删除记录,但我对我采用的方法并不满意。请指导我删除特定日期的重复记录,只保留最新的记录,更好地利用 ActiveRecord API。

谢谢,阿米特·帕特尔

最佳答案

此方法可能会很慢,所以我不推荐它,除非您定期运行它。

Weight.all.each do |weight|
Weight.order("id desc").where(date: weight.date).all.drop(1).each { |w| w.delete }
end

关于mysql - 事件记录 : Delete duplicate records,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10409683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com