Postgres-删除重复的行以确保唯一索引有效

时间:2019-07-05 10:03:03

标签: sql postgresql duplicates postgresql-9.5

我的表格结构如下:

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

这将返回半百万行。因此,手动修复这些问题不是一种选择。

所以我要删除所有重复的文件,同时保留原始文件。

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

成为:

id | foodid | ingredientid
1  | 144    | 531

是否可以通过查询执行此操作?

2 个答案:

答案 0 :(得分:1)

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

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

请参见demo

答案 1 :(得分:0)

DELETE FROM foodingredient a
USING foodingredient b
WHERE a.id > b.id
    AND a.foodid = b.foodid 
    AND a.ingredientid = b.ingredientid;
相关问题