2017-07-25 82 views
1

我需要在同一个表中更新具有不同值的重复行。 我的表是用pgsql中的不同值更新所有重复行

table(id, phoneId(int), deviceId(int), userId(int)) 

有一些记录有相同deviceIdphoneId。例如

id phoneId deviceId userId 
1 23  3434  1235 
2 23  5453  235 <---- same phoneId with 1 record 
3 43  5453  2343 <---- same deviceId with 2 record 
4 23  3434  6347 <---- same deviceId and phoneID with 1 record 

我需要改变的是 - 如果phoneId不是唯一的,设定phoneIduserId(此行)。与deviceId相同。 (如果deviceId不是唯一的,设定deviceIduserId) 所以最终的结果应该是这个

id phoneId deviceId userId 
1 23  3434  1235 
2 235  5453  235 <---- phoneId changed to userId 
3 43  2343  2343 <---- phoneId changed to userId 
4 6347  6347  6347 <---- phoneId and deviceId changed to userId 
+0

问题是你可以得到链。 。 。 P1→D1→P2→D2。你想对这些做什么? –

+0

对不起,你能不能更具体地 – heavymetal91

回答

1

只需更新复制phoneids然后复制deviceids(假设表名是“T”)

UPDATE t SET phoneid=userid FROM (SELECT count(*),phoneid FROM t GROUP BY phoneid HAVING count(*)>1) AS foo WHERE t.phoneid=foo.phoneid; 
UPDATE t SET deviceid=userid FROM (SELECT count(*),deviceid FROM t GROUP BY deviceid HAVING count(*)>1) AS foo WHERE t.deviceid=foo.deviceid;
+0

非常感谢你,救我一天:D – heavymetal91