在pgsql

时间:2017-07-25 14:06:45

标签: sql postgresql

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

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不唯一,请将phoneId设置为userId(来自此行)。同样在deviceId。 (如果deviceId不唯一,请将deviceId设置为userId) 所以最终的结果应该是这个

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

1 个答案:

答案 0 :(得分: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;