2012-05-02 7 views
0

특정 날짜에 여러 레코드가있는 경우 해당 날짜의 최신 레코드를 제외한 모든 레코드를 제거하고 싶습니다. 예를 들어, ID가 9, 10, 12 인 테이블 레코드는 같은 날짜입니다. 따라서 ID가 12 인 최신 레코드는 9와 10을 제거해야합니다. 내가 설명한대로 레코드를 제거 할 수 있어요하지만ActiveRecord : 중복 레코드 삭제

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 

여기 중복

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를보다 잘 활용하여 최신 날짜를 유지하는 특정 날짜에 중복 레코드를 제거하도록 안내해주십시오.

감사합니다, 아 미트 파텔

답변

4

이 방법은 실행하지 않는 한 내가하지 않는 것이 좋습니다 느릴 수 정기적으로.

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

느리고 꾸준한하지만 일을했고, 한 시간 운전 I로 사용하는 경우 속도 전에 명확하게 이해할 수있는 코드를 읽는 것을 선호합니다. – lime

0

당신은 날짜에 일을 같은 날짜의 레코드를 제거하지만, 최근에,이 SQL 쿼리를 시도 할 수 있습니다

DELETE FROM weights USING weights weight WHERE (CAST(weights.date as Date) = CAST(weight.date as Date) AND weights.id < weight.id);