隨着業務的發展。某些業務表會達到很高的量級。這時候某些業務若是牽扯到修改數據結構,就不是簡單的alter table
能搞定的事情了sql
話很少說,直接上方案:數據結構
graph LR 複製一個新表 --> 修改表結構 -->拷貝數據 --> 重命名新表 ---> 刪除老表
該方案:速度很快的。幾百萬數據不到1分鐘就搞定了(跟表字段數有關,以實際爲準,建議分批拷貝)大數據
如下以表A爲例子code
CREATE TABLE `A` ( `id` int(11) NOT NULL AUTO_INCREMENT, `is_delete` tinyint(1) DEFAULT NULL, `type` tinyint(4) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
複製一個新表,表結構跟老表一摸同樣索引
create table A_new like A;
修改表結構(這裏以增長字段爲例)table
alter table A_new add column `status` tinyint(8) DEFAULT NULL;
拷貝數據class
insert into A_new (id, is_delete, type) select id, is_delete, type from A
ps:select
若是是增刪索引,能夠使用下面的sqlim
insert into A_new select * from A
若是數據量較大,能夠使用條件語句,分批拷貝(這裏以id爲例,通常都以create_time爲條件)命名
insert into A_new (id, is_delete, type) select id, is_delete, type from A where id > 100000
修改表名
rename table `A` to `A_bak`; rename table `A_new` to `A`;