第一,基礎方法
增加字段基本方法,該方法適合十幾萬的數據量,可以直接進行加字段操作。
ALTER TABLE tbl_tpl ADD title(255) DEFAULT '' COMMENT '標題' AFTER id;
但是,線上的一張表如果數據量很大,執行加字段操作就會鎖表,這個過程可能需要很長時間甚至導致服務崩潰,那么這樣操作就有風險。
第二,臨時表方法
思路如下:
① 創建一個臨時的新表,首先復制舊表的結構(包含索引)
create table new_table like old_table;
② 給新表加上新增的字段,注意,此時新表是空表,加字段很快;
③ 把舊表的數據復制過來
insert into new_table(filed1,filed2…) select filed1,filed2,… from old_table
④ 刪除舊表,重命名新表的名字為舊表的名字
drop table old_table; alter table new_table rename old_table;
不過這里需要注意,執行第三步的時候,可能這個過程也需要時間,這個時候有新的數據進來,所以原來的表如果有字段記錄了數據的寫入時間就最好了,可以找到執行這一步操作之后的數據,並重復導入到新表,直到數據差異很小。不過還是會可能損失極少量的數據。
所以,如果表的數據特別大,同時又要保證數據完整,最好停機操作。
第三,從庫加,主從切換
1.在從庫進行加字段操作,然后主從切換;
2.使用第三方在線改字段的工具。
大表加索引:
create table to_pub_user_new like to_pub_user; create index idx_pub_user_delete_flag on to_pub_user_new (delete_flag); insert into to_pub_user_new select * from to_pub_user; drop table to_pub_user; alter table to_pub_user_new rename to_pub_user;