使用添加的唯一约束删除列中的重复值

时间:2017-05-29 21:50:25

标签: sql

我有一个带有displayName列的表,我添加了一个" unique"约束到。我正在尝试编写一个迁移,将任何非唯一的displayName设置为null,只保留displayName的用户ID较低。这是我的疑问:

UPDATE "User" SET "displayName" = NULL
            WHERE id IN (SELECT id,
                        FROM (SELECT id,
                                  ROW_NUMBER() OVER (partition BY "displayName" ORDER BY id) AS rnum
                              FROM "User") t
                        WHERE t.rnum > 1);

当我尝试运行迁移时,我正在回复"错误:语法错误在或附近" FROM""。

由于

2 个答案:

答案 0 :(得分:1)

为什么不把它写成:

UPDATE "User"
    SET "displayName" = NULL
    WHERE id > (SELECT MIN(u2.id)
                FROM "User" u2
                WHERE u2."displayName" = u."displayName"
               );

无论您使用何种数据库,这也应该能够利用"User"("displayName", id)上的索引。

答案 1 :(得分:0)

更简单的方法是使用CTE或Sub-Query,就像这样......

WITH X AS 
(
SELECT id
     , [displayName] 
     , ROW_NUMBER() OVER (partition BY [displayName] ORDER BY id) AS rnum
FROM [User]
)
UPDATE X 
 SET [displayName] = NULL
WHERE rnum > 1 

OR

UPDATE X
 SET [displayName] = NULL 
FROM (
        SELECT id
             , [displayName] 
             , ROW_NUMBER() OVER (partition BY [displayName] ORDER BY id) AS rnum
        FROM [User]
     ) x
WHERE rnum > 1 

另外,对显示名称的唯一约束确实是:S ....