不重复!!! 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 |
如何重置主键?
答案 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
代替199
,2
代替200
等等,您可以:
DELETE FROM ids1
ALTER TABLE ids1 AUTO_INCREMENT = 1