Mysql id重新排序

問題背景: 在使用刪除記錄之後,自增的id不會應爲記錄的更改而重新編排,從而導致id的斷層現象.
有以下方法:

  • 重置清空id (在不需要所有的記錄的情況下,該方法會將表清空)
  • 刪除id字段並且重建(全部重新排序)
  • 重新設置排序起始(在最大編號之後繼續排序)

一: 重置清空id (在不需要所有的記錄的情況下,該方法會將表清空)

命令:

truncate table 表名

https://jingyan.baidu.com/article/22a299b5fecb789e18376a66.html

二:刪除id字段並且重建

alter table 表名 drop 字段;
alter table 表名 add 字段 int(3) not null first;
alter table 表名 modify column 字段 int( 3 ) not null auto_increment,add primary key(字段);
select * from 表名 order by 字段  ;
--------------------------------------------------------------------------------------------------
例如:
alter table category drop id;
alter table category add id int(3) not null first;
alter table category modify column id int( 3 ) not null auto_increment,add primary key(id);
select * from category  order by id  ;

該方法會將所有的記錄重新排序

https://blog.csdn.net/weixin_42321963/article/details/82751622

三:重新設置排序起始

alter table 表名 AUTO_INCREMENT=n
例如:
alter table admin  AUTO_INCREMENT=1

該方法會根據已有的記錄找出最大的編號,並且在這之後往下排序,不會將中間缺少的序號補上

https://blog.csdn.net/qq_42690512/article/details/95618558

發佈了18 篇原創文章 · 獲贊 1 · 訪問量 697
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章