MySQL 添加索引和字段,修改数据类型
1、添加索引的时候在会话级别关闭写入binlog功能,就不会传到从库,其它从库分别执行,执行完毕检测所有从库执行完成。
例如:
set session sql_log_bin=off;
alter table BI_AppointmentOrder_Cyh add index idx_IdNo (IdNo);
2、添加字段,如果表小,低于5万多条,可以直接主库上执行alter,一定不能使用关闭binlog功能(set session sql_log_bin=off;)。
使用pt-online-schema-change工具添加
pt-online-schema-change --user=root --password=密码 -P3306 --critical-load="Threads_running=500" --no-drop-old-table --alter "add column name varchar(32)" --charset=utf8 D=库名,t=表名 --print --dry-run
pt-online-schema-change --user=root --password=密码 -P3306 --critical-load="Threads_running=500" --no-drop-old-table --alter "add column name varchar(32)" --charset=utf8 D=库名,t=表名 --print –execute
3、 修改数据类型,根据5.7官方文档介绍使用onlineDDL,小表直接在主库执行。大表用pt-online-schema-change工具添加。
例如:
pt-online-schema-change --user=root -pxxxxx -hlocalhost --critical-load="Threads_running=500" --no-drop-old-table --alter " change column StartDate StartDate datetime DEFAULT NULL COMMENT '开始时间'" --charset=utf8 D=hp_cougar_transfer,t=BT_DoctorStopSchedule --print --dry-run
pt-online-schema-change --user=root -pxxxxx -hlocalhost --critical-load="Threads_running=500" --no-drop-old-table --alter " change column StartDate StartDate datetime DEFAULT NULL COMMENT '开始时间'" --charset=utf8 D=hp_cougar_transfer,t=BT_DoctorStopSchedule --print –execute
注意:pt-online-schema-change执行后会保留旧表_开头,建议保留3个月。
4、创建表,一定要检测字符集、引擎和主键。