我需要更新 mySQL 数据库中的一行,但在存在约束时无法执行此操作。
该约束要求两列的组合是唯一的。
例如,名字和姓氏字段必须是唯一的。 SHOW CREATE TABLE
用户可能包含如下内容:
UNIQUE KEY `uniquePortTermCode` (`firstname`,`lastname`)
当我尝试更新时,我违反了此 key ,因此收到错误:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'Bob-Smith' for key 'uniqueFirstnameLastname'
假设我需要交换具有相同姓氏的两个用户的名称。所以我想将 Bob Smith 设置为 Jim Smith,并且我想将 Jim Smith 设置为 Bob Smith。当我尝试第一个更新语句时,我将遇到唯一键错误。
我认为解决方法是SETforeign_key_checks=0
,但由于变量表明这仅适用于外键,而不是唯一键,因此我仍然收到错误。
我还看到 mySQL unique_checks
中有一个变量,但将其设置为 false 仍然不能解决我的问题,我仍然收到错误。
有没有办法在执行此操作时忽略唯一键,而无需像滑动拼图那样更改周围的数据?
最佳答案
如果您想交换“Bob Smith”和“Jim Smith”,您可以通过三个更新来完成:
update table t
set firstname = 'In the process of swapping names from Bob to Jim'
where firstname = 'Bob' and lastname = 'Smith';
update table t
set firstname = 'Bob'
where firstname = 'Jim' and lastname = 'Smith';
update table t
set firstname = 'Jim'
where firstname = 'In the process of swapping names from Bob to Jim' and lastname = 'Smith';
我建议将它们包装在单个事务中,以便它们在逻辑上作为单个 block 执行,并将其放入存储过程中。
另一种方法是删除或禁用对表的检查。这会产生影响——在多用户环境中,其他线程上可能会发生错误。或者,系统可能会关闭并在关闭检查的情况下恢复。
这种方法中可能发生的最糟糕的情况是记录的名字非常尴尬,但可以很容易地修复。 (如果交易正常,这种情况就不会发生。)
关于mySQL UPDATE,同时忽略表约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27059659/