删除基于多列的重复记录 [英] Delete duplicate records based on multiple columns

查看:91
本文介绍了删除基于多列的重复记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的系统中,我们每小时从外部数据库进行一次导入。由于导入脚本中的错误,现在有一些重复的记录。

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.

在任何记录具有相同的:legacy_id <的情况下,将视为重复记录/ code>和:company

A duplicate is deemed where any record has the same :legacy_id and :company.

我可以运行什么代码来查找和删除这些重复项?

What code can I run to find and delete these duplicates?

我正在玩这个游戏:

Product.select(:legacy_id,:company).group(:legacy_id,:company).having("count(*) > 1")

似乎返回了一些重复项,但我不确定如何从那里删除?

It seemed to return some of the duplicates, but I wasn't sure how to delete from there?

有什么想法吗?

推荐答案

您可以尝试以下方法:

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

或纯SQL:

delete from products
where id not in ( 
   select min(p.id) from products p group by p.legacy_id, p.company
)

这篇关于删除基于多列的重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆