问题描述
我正在尝试迁移到 aurora MysqL,但遇到自动增量问题。使用 aurora MysqL:
create table test (id int NOT NULL AUTO_INCREMENT,Primary Key(id));
insert into test (id) values(0);
insert into test (id) values(0);
insert into test (id) values(0);
update test set id=100 where id=3;
select * from test;
+-----+
| id |
+-----+
| 1 |
| 2 |
| 100 |
+-----+
insert into test (id) values(0);
select * from test;
+-----+
| id |
+-----+
| 1 |
| 2 |
| 4 |
| 100 |
+-----+
With MysqL or MariaDb the last result is:
+-----+
| id |
+-----+
| 1 |
| 2 |
| 100 |
| 101 |
+-----+
请注意,aurora MysqL“填补了”空白,因为 MysqL 保持最大值并使用它。
我可以配置 aurora MysqL 以保持相同的自动增量行为吗?如果是这样,如何?
解决方法
迁移表后,您可以更改自动增量值。
语法有点复杂,因为无法直接使用带有 ALTER TABLE ... AUTO_INCREMENT
的查询或变量,但您可以这样做:
SET @maxid = (SELECT MAX(id) FROM test);
set @sql = concat('ALTER TABLE test AUTO_INCREMENT = ',@maxid + 50);
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
你可以用这个fiddle