Reorder / reset auto increment primary key

后端 未结 15 1432
北荒
北荒 2020-11-22 04:39

I have a MySQL table with an auto increment primary key. I deleted some rows in the middle of the table. Now I have, for example, something like this in the ID column: 12, 1

15条回答
  •  -上瘾入骨i
    2020-11-22 05:07

    for InnoDB, do this (this will remove all records from a table, make a bakcup first):

    SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS ;
    SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION ;
    SET NAMES utf8 ;
    SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 ;
    SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 ;
    SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' ;
    SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 ;
    /* ================================================= */
    
    drop table tablename;
    CREATE TABLE `tablename` (
       table structure here!
    
    ) ENGINE=InnoDB AUTO_INCREMENT=  ai number to reset  DEFAULT CHARSET= char set here;
    
    
    
    /* ================================================= */
    SET SQL_MODE=@OLD_SQL_MODE ;
    SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS ;
    SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS ;
    SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT ;
    SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS ;
    SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION ;
    SET SQL_NOTES=@OLD_SQL_NOTES ;
    

提交回复
热议问题