Skip to content

Instantly share code, notes, and snippets.

@mimosa
Last active August 29, 2015 14:10
Show Gist options
  • Save mimosa/99ce972c285bcc046dc8 to your computer and use it in GitHub Desktop.
Save mimosa/99ce972c285bcc046dc8 to your computer and use it in GitHub Desktop.
MySQL 去重
# -*- encoding: utf-8 -*-
class ActiveRecord::Base
class << self
# 去重
def divorce_by(field_name, id = :id)
ids = twin_ids_by(field_name, id)
self.where(id: ids).delete_all unless ids.empty?
end
# 找出重复的 ids
def twin_ids_by(field_name, id = :id)
self.select(id).twins_by(field_name).uniq.pluck(id)
end
# 找出重复记录
def twins_by(field_name, limit = 1)
group(field_name).having('COUNT(?) > ?', field_name, limit)
end
# 反选字段
def unselect(*args)
self.select(self.column_names - args.map(&:to_s))
end
end
end
# 列出所有表名
module Kernel
def tables
ActiveRecord::Base.connection.tables
end
end
@yangxing-star
Copy link

ids = User.select(:id).group(field_name).having("count(#{field_name}) > 1").pluck(:id)
User.where(id: ids).delete_all unless ids.empty?

@mimosa
Copy link
Author

mimosa commented Nov 22, 2014

感谢 @yangxing-star 效率高很多。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment