重置主键auto_increment [part2]

时间:2014-05-07 11:41:25

标签: mysql sql

不重复!!! Reset primary key auto_increment

How to reset AUTO_INCREMENT in MySQL?

mysql> CREATE TABLE ids1(id int not null PRIMARY KEY AUTO_INCREMENT,num int) AUT
O_INCREMENT=199;
Query OK, 0 rows affected (0.26 sec)

mysql> INSERT INTO ids1(num) VALUES(1),(2),(3),(4);
Query OK, 4 rows affected (0.04 sec)

mysql> SELECT * FROM ids1;
+-----+------+
| id  | num  |
+-----+------+
| 199 |    1 |
| 200 |    2 |
| 201 |    3 |
| 202 |    4 |
+-----+------+
4 rows in set (0.00 sec)

mysql> ALTER TABLE ids1 AUTO_INCREMENT=7;  
Query OK, 4 rows affected (0.34 sec)
Records: 4  Duplicates: 0  Warnings: 0

AND问题:

mysql> INSERT INTO ids1(num) VALUES(77),(72);
Query OK, 2 rows affected (0.04 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM ids1;
+-----+------+
| id  | num  |
+-----+------+
| 199 |    1 |
| 200 |    2 |
| 201 |    3 |
| 202 |    4 |
| 203 |   77 |
| 204 |   72 |
+-----+------+
6 rows in set (0.00 sec)

但是为什么当auto_increment> last_inserd_id然后

mysql> ALTER TABLE ids1 AUTO_INCREMENT=1027;
Query OK, 8 rows affected (0.18 sec)
Records: 8  Duplicates: 0  Warnings: 0

mysql> INSERT INTO ids1(num) VALUES(77),(72);
Query OK, 2 rows affected (0.03 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM ids1;
+------+------+
| id   | num  |
+------+------+
|  199 |    1 |
|  200 |    2 |
|  201 |    3 |
|  202 |    4 |
|  203 |   77 |
|  204 |   72 |
|  205 |   77 |
|  206 |   72 |
| 1027 |   77 |
| 1028 |   72 |

如何重置主键?

1 个答案:

答案 0 :(得分:2)

阅读官方MySQL文档和评论(*),似乎无法实现。 使用指令ALTER TABLE ids1 AUTO_INCREMENT = n,您可以重置该值,但不能小于先前为该列插入的最大值。

(*)http://dev.mysql.com/doc/refman/5.7/en/example-auto-increment.html

如果要更改记录,请将值放入列" ID"从1开始(即1代替1992代替200等等,您可以:

  1. 制作表格的副本
  2. 删除表格的所有记录:DELETE FROM ids1
  3. 重置自动增量列:ALTER TABLE ids1 AUTO_INCREMENT = 1
  4. 再次插入所有记录