如果你有一張表,你的主鍵是ID,然后由於測來測去的原因,你的ID不是從1開始連續的自增了。
終於有一天,使用這張表的某個系統要導入正式數據了,強迫症這時候就表現的明顯了,渾身不自在,
這時候你就需要將這個主鍵ID重置一波了,方法是在這張表中新增一個字段,將ID里面的數據復制過去,
然后刪除ID字段,接着新建一個ID字段,再接着將id字段自增且設為主鍵,最后將這個新增的ID列挪到第一列,
將那個用於復制最初ID內容的新增字段刪除,一切OK.
1、在要操作的表 tablename 中新增一個字段 old_id;
alter table tablename add old_id int(10) not null;
2、將 id 字段的數據復制給 old_id;
update tablename set old_id=id;
3、刪除 id 字段;
alter table tablename drop id;
4、新增一個 id 字段;
alter table tablename add id int(10) not null;
5、將這個新增的 id 字段設置為自增主鍵;
alter table tablename modify column id int(10) not null auto_increment, add primary key (id);
6、刪除 old_id 列;
alter table tablename drop column old_id;
7、將最新的 id 列挪到最前面;
alter table tablename modify id int(10) first;