如何更改从特定数字开始的值

时间:2014-04-30 14:58:48

标签: mysql

我有一个列'id',现在值为1,2,3,4等。这是我的主要列,设置为自动增量。

但我想更新此列并更改所有值,从某个数字开始。不重置自动增量,而是改变已存在的内容。

因此,例如,我希望它从1000开始,然后每行增加1,增加到1001,1002等。如何做到这一点?

感谢。

1 个答案:

答案 0 :(得分:2)

自我解释测试:

> create table ainc(id int auto_increment primary key);
Query OK, 0 rows affected (0.14 sec)

> insert into ainc values (null), (null), (null), (null);
Query OK, 4 rows affected (0.04 sec)
Records: 4  Duplicates: 0  Warnings: 0

> select * from ainc;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
+----+
4 rows in set (0.01 sec)

> update ainc set id = id + 1 where id > 2;
ERROR 1062 (23000): Duplicate entry '4' for key 'PRIMARY'

> update ainc set id = id + 1 where id > 2 order by id desc;
Query OK, 2 rows affected (0.04 sec)
Rows matched: 2  Changed: 2  Warnings: 0

> select * from ainc;
+----+
| id |
+----+
|  1 |
|  2 |
|  4 |
|  5 |
+----+

摘要:只需在update语句中使用受支持的order by即可。

然后不要忘记用

调整你的auto_increment值
ALTER TABLE ainc AUTO_INCREMENT = 5;

或者你会得到这个:

> insert into ainc values (null); 
ERROR 1062 (23000): Duplicate entry '5' for key 'PRIMARY'

> ALTER TABLE ainc AUTO_INCREMENT = 5;
Query OK, 4 rows affected (0.52 sec)
Records: 4  Duplicates: 0  Warnings: 0

> insert into ainc values (null);
Query OK, 1 row affected (0.01 sec)

> select * from ainc;
+----+
| id |
+----+
|  1 |
|  2 |
|  4 |
|  5 |
|  6 |
+----+
相关问题