【问题标题】:Rails 5 select duplicate by two columns or attributes?Rails 5选择两列或属性重复?
【发布时间】:2020-07-31 19:35:09
【问题描述】:

我有一个模型用户,我的数据库(postgres)被迁移了重复的值。我想按两列选择重复行:group_code 和birthdate: 例如。

id | group_code | birthdate
2  | 345        |  1980-05-05
3  | 261        |  1994-03-06
4  | 876        |  1997-09-16
5  | 345        |  1980-05-05

预期结果(使用活动记录):ID 为 2 和 5 的用户

【问题讨论】:

    标签: sql ruby postgresql activerecord ruby-on-rails-5


    【解决方案1】:

    你可以使用exists:

    select t.*
    from table t
    where exists (select 1 
                  from table t1 
                  where t1.group_code = t.group_code and 
                        t1.birthdate = t.birthdate and 
                        t1.id <> t.id
                 );
    

    【讨论】:

    • 我的意思是使用 rails 控制台的代码,没有 sql。还是谢谢
    【解决方案2】:

    您也可以使用count。这是Demo

    select
      id,
      group_code,
      birthdate
    from
    (
      select
        *,
        count(*) over (partition by group_code, birthdate) as cnt
      from myTable
    ) val
    where cnt > 1 
    

    输出:

    id  group_code  birthdate
    --------------------------
    2     345       1980-05-05
    5     345       1980-05-05
    

    【讨论】:

    • 不,我的意思是使用 rails 控制台的代码,没有 sql。还是谢谢
    【解决方案3】:

    看起来您只需要一列。看起来有人可能已经创建了两个相同的记录。您可以使用以下代码解决此问题,但也可以查看 here 以避免将来在使用 rails 创建条目时数据库中可能出现重复

    group = Model.where(group_code: 345).first
    parameters = group.attributes
    
    Model.where(group_code: 345).destroy_all
    
    new_group = Model.find_or_create_by(group_code: 345)
    new_group.update_attributes(parameters)
    new_group.save
    

    免责声明: 我自己是 Rails 新手,可能有更好的方法来做到这一点,但这样做是:找到所有符合条件的对象,然后保存这些属性......然后删除 where 关系中的所有对象和重新创建它们。如果您愿意,您甚至可以将日期附加到 .where 中。 Model 是您的型号名称。我也使用过 Rails 3 和 6。我知道它是 Rails 3 的 update_attributes,但较新的版本可能会弃用...尝试更新以更改版本。

    【讨论】:

      猜你喜欢
      • 2021-02-12
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2016-08-30
      • 2012-12-30
      • 2016-01-13
      • 2015-03-01
      相关资源
      最近更新 更多