Mysql/Maridb 更新无效
Mysql/Maridb Update is not working
假设 table 包含类似
的数据
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 违反了通过 unique key
已经存在的 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 上工作是在另一个数据库平台上和一些其他模式上。所以那是静音。
假设 table 包含类似
的数据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 违反了通过 unique key
已经存在的 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 上工作是在另一个数据库平台上和一些其他模式上。所以那是静音。