【问题标题】:How do I delete one row for two duplicate entries in a postgres table?如何删除 postgres 表中两个重复条目的一行?
【发布时间】:2016-11-13 10:47:20
【问题描述】:

除了时间戳列之外,这两行具有所有相同的列 - created_at

我只想保留这些行之一 - 没关系。

这就是我能够根据 created_at 列中的值较小的列来选择可以删除的重复行中的每一个的方法。

 select e.id, e.user_id, e.r_needed, e.match, e.status, e.stage, e.created_at 
    from employee e, employee e2 where e.id=e2.id and e.user_id=e2.user_id and 
     e.status = 12 and e2.status=12 and e.stage=false and e2.stage=false and 
     e.match=true and e2.match=true and e.user_id=12 and e.r_needed=true and e2.r_needed=true
     and e.created_at<e2.created_at and DATE(e.created_at)='2015-10-08';

但是,不知道如何删除这一行,这样两个重复项都不会被删除,而只有上面选择的那些会被删除?

基本上,我想删除与上面我的选择查询中的列匹配的所有行以及 created_at 值较小的行。

我的表没有主键或唯一键。

【问题讨论】:

  • 将行号与适当的分区一起使用,然后删除行号仅为 1 的位置。
  • @TimBiegeleisen:最好使用 row_number > 1 代替 :)
  • 您能否举例说明如何在上面的查询中使用它?

标签: sql postgresql duplicates


【解决方案1】:

您可以使用关联子查询而不是连接:

select * from employee e
where exists
 ( select * from employee e2 
   where e.id=e2.id and e.user_id=e2.user_id 
     and e.status = 12 and e2.status=12 and e.stage=false 
     and e2.stage=false and e.match=true and e2.match=true 
     and e.user_id=12 and e.r_needed=true and e2.r_needed=true
     and e.created_at<e2.created_at 
     and DATE(e.created_at)='2015-10-08'
 );

如果这会正确返回重复的行,您可以切换到 delete 而不是 select *

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 1970-01-01
    • 2022-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    相关资源
    最近更新 更多