更新以用另一个替换特定值,除非它已经存在

Update to replace specific value with another except when it already exists

我有一个 table 值如下:

...
jack     |  woo
...
james    |  poo
james    |  woo
...
john     |  poo
...

两列也有 UNIQUE 约束

我想把所有的'poo'都改成'woo',只要不违反约束,然后删除剩下的'poo',为了得到这个table:

...
jack     |  woo
...
james    |  woo
...
john     |  woo
...

我为第一步所做的努力:

UPDATE MyTable SET lastname='woo' WHERE lastname='poo'

Result: UNIQUE constraint failed: [..]

UPDATE MyTable SET lastname='woo' WHERE lastname='poo'
AND NOT EXISTS (SELECT 1 FROM MyTable t2 WHERE t2.lastname='woo')

Result: [..] 0 rows affected

这是我在 sqlite-browser 中执行的操作,我可能只需要它几十次。所以解决方案不需要非常高效或单一查询。

因为我的数据库不是 'live' 我也可以,例如,暂时禁用约束检查,执行我的第一个查询,然后清理重复项(如何?)

您应该关联子查询:

UPDATE MyTable AS t1 
SET lastname = 'woo' 
WHERE t1.lastname = 'poo'
  AND NOT EXISTS (SELECT 1 FROM MyTable t2 WHERE (t2.firstname, t2.lastname) = (t1.firstname, 'woo'));

然后删除剩余的行:

DELETE FROM MyTable WHERE lastname = 'poo';

参见demo