【问题标题】:Postgres - Deleting duplicates rows to ensure unique index worksPostgres - 删除重复行以确保唯一索引有效
【发布时间】:2019-07-05 18:21:32
【问题描述】:

我的表格结构如下:

id | foodid | ingredientid

我想创建一个唯一索引如下:

create unique index foodingredient_foodid_ingredientid_uindex
    on foodingredient (foodid, ingredientid);

问题是该表包含大量重复的 foodid 和 Ingredientid 条目。这些是不必要的,我想删除它们。

如果我跑:

select count(*)
from foodingredient
group by foodid, ingredientid
having count(*) > 1
order by count desc

这将返回 50 万行。所以手动修复这些不是一种选择。

所以我想要做的是删除所有重复项,同时保留原件。

id | foodid | ingredientid
1  | 144    | 531
2  | 144    | 531
3  | 144    | 531
4  | 144    | 531

变成:

id | foodid | ingredientid
1  | 144    | 531

有没有办法通过查询来做到这一点?

【问题讨论】:

    标签: sql postgresql duplicates postgresql-9.5


    【解决方案1】:

    你可以通过存在来做到这一点:

    delete from foodingredient t
    where exists (
      select 1 from foodingredient
      where foodid = t.foodid and ingredientid = t.ingredientid and id < t.id
    )
    

    请参阅demo

    【讨论】:

      【解决方案2】:
      DELETE FROM foodingredient a
      USING foodingredient b
      WHERE a.id > b.id
          AND a.foodid = b.foodid 
          AND a.ingredientid = b.ingredientid;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-02
        • 1970-01-01
        • 1970-01-01
        • 2016-07-06
        • 2020-10-01
        • 1970-01-01
        相关资源
        最近更新 更多