我是小菜。
在此请教个问题:
设置了auto-increment的主键如何重用?例如:
我设置id为primary key ,auto-increment。已经insert了9条记录,id值当前自动增加到9,我delete了第9项后,重新insert一条记录,为什么id不是9,而是10呢?9现在不是已经没有记录了吗?
请问这是正常?如果我要重用之前的键值,让id仍为9,该怎么做呢?(除了指定id的值以外)

解决方案 »

  1.   

    alter table tablename auto_increment=9;mysql> create table migoumigou(id int primary key auto_increment,col int);
    Query OK, 0 rows affected (0.08 sec)mysql> insert into migoumigou (col) values (1),(2),(3),(4);
    Query OK, 4 rows affected (0.01 sec)
    Records: 4  Duplicates: 0  Warnings: 0mysql> select * from migoumigou;
    +----+------+
    | id | col  |
    +----+------+
    |  1 |    1 |
    |  2 |    2 |
    |  3 |    3 |
    |  4 |    4 |
    +----+------+
    4 rows in set (0.00 sec)mysql> delete from migoumigou where id>2;
    Query OK, 2 rows affected (0.06 sec)mysql> select * from migoumigou;
    +----+------+
    | id | col  |
    +----+------+
    |  1 |    1 |
    |  2 |    2 |
    +----+------+
    2 rows in set (0.00 sec)mysql> alter table migoumigou auto_increment=3;
    Query OK, 2 rows affected (0.14 sec)
    Records: 2  Duplicates: 0  Warnings: 0mysql> insert into migoumigou (col) values (10),(20);
    Query OK, 2 rows affected (0.06 sec)
    Records: 2  Duplicates: 0  Warnings: 0mysql> select * from migoumigou;
    +----+------+
    | id | col  |
    +----+------+
    |  1 |    1 |
    |  2 |    2 |
    |  3 |   10 |
    |  4 |   20 |
    +----+------+
    4 rows in set (0.00 sec)mysql>
      

  2.   

    楼主的问题我也遇到过,呵呵,你需要自己恢复auto_increment的值,像楼上说的那样。