change auto_increment within same table using subquery mysql

后端 未结 4 1164
青春惊慌失措
青春惊慌失措 2021-01-14 15:56

I am using mysql. I have a database table with auto_increment counter set. Now because of a requirement I need to leave starting 100 ids free and move all existing records s

4条回答
  •  迷失自我
    2021-01-14 16:34

    In response to @Peter, it appears that you will have to update the AUTO_INCREMENT value after changing changing an existing one. The following example was done on MariaDB 10.0.12:

    MariaDB [test]> show create table m;
    +-------+--------------------------------------------------------+
    | Table | Create Table                                           |
    +-------+--------------------------------------------------------+
    | m     | CREATE TABLE `m` (                                     |
    |       |`id` int(10) unsigned NOT NULL AUTO_INCREMENT,          |
    |       |`t` varchar(10) NOT NULL DEFAULT '',                    |  
    |       |PRIMARY KEY (`id`)                                      |
    |       |) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
    +-------+--------------------------------------------------------+
    1 row in set (0.00 sec)
    
    MariaDB [test]> insert into m (t) values ('a'),('b');
    Query OK, 2 rows affected (0.03 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    
    MariaDB [test]> select * from m;
    +----+---+
    | id | t |
    +----+---+
    |  1 | a |
    |  2 | b |
    +----+---+
    2 rows in set (0.00 sec)
    
    MariaDB [test]> update m set id=id+10;
    Query OK, 2 rows affected (0.05 sec)
    Rows matched: 2  Changed: 2  Warnings: 0
    
    MariaDB [test]> select * from m;
    +----+---+
    | id | t |
    +----+---+
    | 11 | a |
    | 12 | b |
    +----+---+
    2 rows in set (0.00 sec)
    
    MariaDB [test]> show create table m;
    +-------+--------------------------------------------------------+
    | Table | Create Table                                           |
    +-------+--------------------------------------------------------+
    | m     | CREATE TABLE `m` (                                     |
    |       |`id` int(10) unsigned NOT NULL AUTO_INCREMENT,          |
    |       |`t` varchar(10) NOT NULL DEFAULT '',                    |  
    |       |PRIMARY KEY (`id`)                                      |
    |       |) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1 |
    +-------+--------------------------------------------------------+
    1 row in set (0.00 sec)
    
    MariaDB [test]> insert into m (t) values ('c');
    Query OK, 1 row affected (0.04 sec)
    
    MariaDB [test]> select * from m;
    +----+---+
    | id | t |
    +----+---+
    |  3 | c |
    | 11 | a |
    | 12 | b |
    +----+---+
    3 rows in set (0.00 sec)
    
    MariaDB [test]>
    

提交回复
热议问题