Prerequisites
structure
mysql> desc tt1; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(20) | NO | UNI | NULL | | +-------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)
content
mysql> select * from tt1; +----+------+ | id | name | +----+------+ | 1 | aaa | +----+------+ 1 row in set (0.00 sec)Error inserting duplicate records
mysql> insert into tt1 (name)values('aaa');
ERROR 1062 (23000): Duplicate entry 'aaa' for key 'name'
re-operate after modification
mysql> insert into tt1 (name)values( 'bbb');
Query OK, 1 row affected (0.00 sec)
see the content again
mysql> select * from tt1; +----+------+ | id | name | +----+------+ | 1 | aaa | | 3 | bbb | +----+------+ 2 rows in set (0.00 sec)Problem: id is not the 2 we need, but 3
reasons: wrong insert operation, which has affected the operation of auto-increment + 1, the
command is correct, but the data does not meet the table requirements.
As long as the command is good, auto-increment + 1 Running, no problem.
Solution Before
each insert, set auto_increment=1
, that is, run two commands to complete the correct operation
alter table tt1 auto_increment=1;
insert into tt1 (name)values('ccc'); The
execution is as follows:
mysql> alter table tt1 auto_increment=1; Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> insert into tt1 (name)values('ccc'); Query OK, 1 row affected (0.00 sec)
mysql> select * from tt1; +----+------+ | id | name | +----+------+ | 1 | aaa | | 3 | bbb | | 4 | ccc | +----+------+ 3 rows in set (0.00 sec)t