Delete duplicate records based on multiple columns

前端 未结 1 713
梦毁少年i
梦毁少年i 2021-02-12 21:05

In our system we run hourly imports from an external database. Due to an error in the import scripts, there are now some duplicate records.

A duplicate is deemed where a

相关标签:
1条回答
  • 2021-02-12 21:25

    You can try the following approach:

    Product.where.not(
      id: Product.group(:legacy_id, :company).pluck('min(products.id)')
    ).delete_all
    

    Or pure sql:

    delete from products
    where id not in ( 
       select min(p.id) from products p group by p.legacy_id, p.company
    )
    
    0 讨论(0)
提交回复
热议问题