mysql - 如何使用 Rails 删除 MySQL 中的重复项?

标签 mysql sql ruby-on-rails

我必须下表:

关系

[id,user_id,status]
1,2,sent_reply
1,2,sent_mention
1,3,sent_mention
1,4,sent_reply
1,4,sent_mention

我正在寻找一种删除重复项的方法,以便只保留以下行:

1,2,sent_reply
1,3,sent_mention
1,4,sent_reply

(最好使用 Rails)

最佳答案

我知道这已经晚了,但我找到了一个使用 Rails 3 的好方法。虽然可能有更好的方法,但我不知道这将如何处理 100,000 多行数据,但是这应该让你走上正确的 rails 。

# Get a hash of all id/user_id pairs and how many records of each pair
counts = ModelName.group([:id, :user_id]).count
# => {[1, 2]=>2, [1, 3]=>1, [1, 4]=>2}

# Keep only those pairs that have more than one record
dupes = counts.select{|attrs, count| count > 1}
# => {[1, 2]=>2, [1, 4]=>2}

# Map objects by the attributes we have
object_groups = dupes.map do |attrs, count|
  ModelName.where(:id => attrs[0], :user_id => attrs[1])
end

# Take each group and #destroy the records you want.
# Or call #delete instead to save time if you don't need ActiveRecord callbacks
# Here I'm just keeping the first one I find.
object_groups.each do |group|
  group.each_with_index do |object, index|
    object.destroy unless index == 0
  end
end

关于mysql - 如何使用 Rails 删除 MySQL 中的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5638543/

相关文章:

python - 如何使用saltstack安装和配置mysql

sql - 计算组内的百分比

ruby-on-rails - 在 Rails 中访问模型属性

ruby-on-rails - 错误后设计重定向

ruby-on-rails - 评论投票与 acts as votable

PHP/MYSQL - 如何将 2 个或更多结果传递到动态页面?

php - 如何让用户在一个简单的 php-mysql 站点中的帖子中插入图像??如何将文件名存储在 mysql 数据库中?

sql - 快速 SQL 问题!按出现次数最多的属性排序

php - 通过 SQL 查询过滤并填充 <select>

mysql - 为多行创建触发器