假设一个表包含类似的数据
MariaDB [c]> select * from t2;
+-----+
| abc |
+-----+
| 1 |
| 3 |
| 5 |
+-----+
假设我的更新命令是
MariaDB [c]> update t2 set abc = abc+2;
它给出以下错误
ERROR 1062 (23000): Duplicate entry '3' for key 'PRIMARY'
虽然上面的命令在 oracle 10g 中运行良好,但这是某种错误还是什么?
最佳答案
以下只是一个说明,而且很琐碎。
create table t2
( id int auto_increment primary key,
abc int not null,
unique key(abc)
);
insert t2(abc) values (1),(3),(5); -- 3 rows added
update t2 set abc = abc+2; -- Error Code 1062: Duplicate entry '3' for key 'abc'
发生上述错误是因为更新按照主键的顺序(也是物理顺序)进行,并且将 1 更改为 3 违反了通过唯一键
已经存在的 3 。理想情况下,最终状态将使一切顺利,这一事实并不能阻止它在那一刻失败。
为了说明在这个高度操纵的示例中的工作原理,知道没有其他数据:
truncate table t2; -- the data wasn't modified but for the paranoid, clear and re-insert
insert t2(abc) values (1),(3),(5); -- 3 rows added
尝试自下而上(这样就不会违反唯一约束):
update t2 set abc = abc+2 order by abc desc;
select * from t2;
+----+-----+
| id | abc |
+----+-----+
| 1 | 3 |
| 2 | 5 |
| 3 | 7 |
+----+-----+
它利用了更新语句中的order by
功能。
因此,归根结底是了解您的数据以及您可以逃脱的惩罚。说它在 Oracle 上工作就像你在评论中所做的那样,是在另一个数据库平台上并且使用其他一些模式。所以这是静音。
关于Mysql/Mariadb 更新不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37781492/