我有一个postgresql数据库表称为user_links目前允许以下重复字段:
year,user_id,sid,cid
唯一约束当前是第一个称为“id”的字段,但是我现在想要设置约束,以确保年份,user_id,sid和cid都是唯一的,但是我不能应用约束,因为重复的值已经存在,违反这个约束。
我的问题是,有没有办法找到所有重复?
谢谢
基本思想将使用带有计数聚合的嵌套查询:
select * from yourTable ou where (select count(*) from yourTable inr where inr.sid = ou.sid) > 1
// EDITED 17 Mar 2016
还有另一个好的解决方案(它在评论中提到,但不是每个人都读它们):
select Column1,Column2,count(*) from yourTable group by Column1,Column2 HAVING count(*) > 1
或(较短)
SELECT (yourTable.*)::text,count(*) FROM yourTable GROUP BY yourTable.* HAVING count(*) > 1