【问题标题】:How can I delete equal rows in a table in SQL? [duplicate]如何在 SQL 中删除表中的相等行? [复制]
【发布时间】:2020-07-04 23:44:47
【问题描述】:

我有一个表,其中插入了一些数据。问题是有很多行与其他行相等,我想删除它们,只留下其中的一行。例如:

桌人

    name       pet
---------------------------
    Mike       Dog
    Kevin      Dog
    Claudia    Cat
    Mike       Dog
    Mike       Dog
    Kevin      Snake

如您所见,我们可以多次看到名为MikePerson 有一个Dog。 但我只想看一次。所以更新这个表后我想要的输出是:

    name       pet
---------------------------
    Mike       Dog
    Kevin      Dog
    Claudia    Cat
    Kevin      Snake

如何做到这一点?

【问题讨论】:

  • Person有id列吗?
  • 是的@pilcrow

标签: sql postgresql duplicates sql-delete


【解决方案1】:

最简单的方法可能是重新创建表:

create table temp_t as 
    select distinct name, pet
    from t;

truncate table t;   -- back it up first!

insert into t (name, pet)
    select name, pet
    from temp_t;

create unique index unq_t_name_pet on t(name, pet);

最后一步是防止以后出现这个问题。

【讨论】:

    【解决方案2】:

    您可以使用exists 执行此操作。在明显没有主键的情况下,可以使用system column ctid

    delete from mytable t
    where exists (
        select 1
        from mytable t1
        where t1.name = t.name and t1.pet = t.pet and t1.ctid > t.ctid
    );
    

    【讨论】:

      猜你喜欢
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多