【问题标题】:How do I delete one of my two duplicate rows of data in Postgres?如何在 Postgres 中删除我的两个重复数据行之一?
【发布时间】:2017-03-18 19:03:13
【问题描述】:

我使用的是 Postgres 9.5。我有以下查询,旨在在我的表中查找相同的数据行(但唯一的 ID)。

select e.name, 
       e.day, 
       e.distance, 
       e.created_at, 
       e2.created_at 
from events e, 
     events e2 
where e.name = e2.name 
  and e.distance = e2.distance 
  and e.day = e2.day 
  and e.web_crawler_id = e2.web_crawler_id 
  and e.id <> e2.id 
  and e.web_crawler_id = 1 
order by e.day desc;

我最终想删除其中一个重复的行——因此可能会删除“created_at”日期最大的行。但是我不确定如何编写一个查询来只返回两个相同的行之一。我该怎么做?

【问题讨论】:

    标签: postgresql duplicates sql-delete


    【解决方案1】:

    您可以使用 LIMIT:

    select e.name, e.day, e.distance, e.created_at, e2.created_at from events e, events e2 where e.name = e2.name and e.distance = e2.distance and e.day = e2.day and e.web_crawler_id = e2.web_crawler_id and e.id <> e2.id and e.web_crawler_id = 1 order by e.day desc LIMIT 1;
    

    【讨论】:

      【解决方案2】:

      有很多方法,但在不改变你的 sql 的情况下,你可以做的比 for id 更好:

      select e.name, e.day, e.distance, e.created_at, e2.created_at 
      from events e, events e2
      where e.name = e2.name
      and e.distance = e2.distance
      and e.day = e2.day 
      and e.web_crawler_id = e2.web_crawler_id 
      and e.id > e2.id 
      and e.web_crawler_id = 1 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 2020-07-08
        • 1970-01-01
        • 2016-03-08
        相关资源
        最近更新 更多