使用rails或mysql查询删除mysql数据库中重复记录的最佳方法是什么?
您可以做的是通过以下方式将不同记录复制到新表中:
select distinct * into NewTable from MyTable
这是另一种没有特定语言的想法:
rs = `select a, b, count(*) as c from entries group by 1, 2 having c > 1` rs.each do |a, b, c| `delete from entries where a=#{a} and b=#{b} limit #{c - 1}` end
编辑:
荣誉对奥拉夫为"具有"提示:)
好吧,如果它是一个小桌子,你可以从rails控制台做
class ActiveRecord::Base def non_id_attributes atts = self.attributes atts.delete('id') atts end end duplicate_groups = YourClass.find(:all).group_by { |element| element.non_id_attributes }.select{ |gr| gr.last.size > 1 } redundant_elements = duplicate_groups.map { |group| group.last - [group.last.first] }.flatten redundant_elements.each(&:destroy)
SELECT DISTINCT(req_field) AS field, COUNT(req_field) AS fieldCount FROM table_name GROUP BY req_field HAVING fieldCount > 1
DELETE FROM table_name USING table_name, table_name AS vtable WHERE (table_name.id > vtable.id) AND (table_name.req_field=req_field)
替换req_field和table_name - 应该没有任何问题.