PSQL get duplicate row

﹥>﹥吖頭↗ 提交于 2020-01-07 08:02:17

问题


I have table like this-

id        object_id       product_id          
1         1                1                  
2         1                1                  
4         2                2                  
6         3                2                  
7         3                2                  
8         1                2                  
9         1                1                  

I want to delete all rows except these-

1         1                 1      
4         2                 2
6         3                 2         
9         1                 2         

Basically there are duplicates and I want to remove them but keep one copy intact.

what would be the most efficient way for this?


回答1:


If this is a one-off then you can simply identify the records you want to keep like so:

SELECT MIN(id) AS id
FROM yourtable
GROUP BY object_id, product_id;

You want to check that this works before you do the next thing and actually throw records out. To actually delete those duplicate records you do:

DELETE FROM yourtable WHERE id NOT IN (
  SELECT MIN(id) AS id
  FROM yourtable
  GROUP BY object_id, product_id
);

The MIN(id) obviously always returns the record with the lowest id for a set of (object_id, product_id). Change as desired.



来源:https://stackoverflow.com/questions/23690867/psql-get-duplicate-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!