MySQL自增主键ID重新排序

一、不清空数据

  无外键约束:

  1、删除原有主键

    alter table '表名' drop 'id';

  2、添加新主键字段并设置主键

    alter table '表名' add 'id' int(8) primary key not null auto_increment first;

  有外键约束

  1、删除外键关系

    alter table test1(外键表) drop foreign key test1_ibfk_1(外键名);  

  2、删除主键字段

     alter table test(主键表) drop 'tid'(主键字段); 

  3、重新设置主键字段,以及自增初始值

     alter table test add column 'tid' int(8) primary key auto_increment,auto_incremet=100; 

  4、重新设置外键

        alter table test1 add foreign key(ttid)(需要添加的外键字段) references test(tid);  

二、清空数据

  set foreign_key_checks=0;   取消外键约束

  truncate table 表名

  set foreign_key_checks=1;设置外键约束

  truncate:可以在快速清空表数据的同时还可以使自增列重新从1开始

猜你喜欢

转载自www.cnblogs.com/xing-29391/p/12896476.html