gpt4 book ai didi

sql - Rails(或者可能是 SQL): Finding and deleting duplicate AR objects

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:31 24 4
gpt4 key购买 nike

“位置”类(表示数据库表位置)的 ActiveRecord 对象具有属性“url”、“lat”(纬度)和“lng”(经度)。

此模型上的经纬度组合应该是唯一的。问题是,数据库中有很多位置对象具有重复的经纬度组合。

我需要帮助做以下事情

  1. 找到共享相同的对象经纬度组合。
  2. 如果对象的'url'属性不为空,保留此对象并删除其他重复项。否则只需选择最旧的对象(通过检查属性'created_at') 并删除其他重复项。

由于这是一次性操作,因此也欢迎使用 SQL(兼容 MySQL 5.1)的解决方案。

最佳答案

如果这是一次性的事情,那么我会用 Ruby 来做,而不用太担心效率。我还没有对此进行彻底的测试,检查排序等以确保它在你的数据库上运行它之前完全按照你的要求做:)

keep = []
locations = Location.find(:all)

locations.each do |loc|
# get all Locations's with the same coords as this one
same_coords = locations.select { |l| l.lat == loc.lat and \
l.lng == loc.lng }
with_urls = same_coords.select { |l| !l.url.empty? }

# decide which list to use depending if there were any urls
same_coords = with_urls.any? ? with_urls : same_coords

# pick the best one
keep << same_coords.sort { |a,b| b.created_at <=> a.created_at }.first.id
end

# only keep unique ids
keep.uniq!

# now we just delete all the rows we didn't decide to keep
locations.each do |loc|
loc.destroy unless keep.include?( loc.id )
end

就像我说的,这绝对是糟糕的代码。但有时候,仅仅破解出有效的东西就值得节省时间来思考“更好”的东西,尤其是一次性的。

关于sql - Rails(或者可能是 SQL): Finding and deleting duplicate AR objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/743873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com