Last active
August 29, 2015 14:10
-
-
Save mimosa/99ce972c285bcc046dc8 to your computer and use it in GitHub Desktop.
MySQL 去重
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 |
Author
mimosa
commented
Nov 21, 2014
ids = User.select(:id).group(field_name).having("count(#{field_name}) > 1").pluck(:id)
User.where(id: ids).delete_all unless ids.empty?
感谢 @yangxing-star 效率高很多。
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment