锦囊妙计一: pt-online-schema-change
功能可以在线整理表结构,收集碎片,给大表添加字段和索引。避免出现锁表导致阻塞读写的操作。针对 MySQL 5.7 版本,就可以不需要使用这个命令,直接在线 online DDL 就可以了。
展现过程如下:
由于是测试环境,就不创建一张数据量特大的表,主要让大家理解这个过程。
这是表里面数据的情况和表结构
mysql> select count(*) from su;
+----------+
| count(*) |
+----------+
| 100000 |
+----------+
1 row in set (0.03 sec)
mysql> desc su;
+-------+------------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+------------------+------+-----+-------------------+-----------------------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| c1 | int(11) | NO | | 0 | |
| c2 | int(11) | NO | | 0 | |
| c3 | int(11) | NO | | 0 | |
| c4 | int(11) | NO | | 0 | |
| c5 | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| c6 | varchar(200) | NO | | | |
在线增加字段的过程:
[root@node3 bin]# ./pt-online-schema-change --user=root --password=root123
--host=localhost --alter="ADD COLUMN city_id INT" D=test,t=su --execute
No slaves found. See --recursion-method if host node3 has slaves.
Not checking slave lag because no slaves were found and --check-slave-lag was not specified.
Operation, tries, wait:
analyze_table, 10, 1
copy_rows, 10, 0.25
create_triggers, 10, 1
drop_triggers, 10, 1
swap_tables, 10, 1
update_foreign_keys, 10, 1
Altering `test`.`su`...
Creating new table...
Created new table test._su_new OK.
Altering new table...
Altered `test`.`_su_new` OK.
2017-08-10T14:53:59 Creating triggers...
2017-08-10T14:53:59 Created triggers OK.
2017-08-10T14:53:59 Copying approximately 100163 rows...
2017-08-10T14:54:00 Copied rows OK.
2017-08-10T14:54:00 Analyzing new table...
2017-08-10T14:54:00 Swapping tables...
2017-08-10T14:54:00 Swapped original and new tables OK.
2017-08-10T14:54:00 Dropping old table...
2017-08-10T14:54:00 Dropped old table `test`.`_su_old` OK.
2017-08-10T14:54:00 Dropping triggers...
2017-08-10T14:54:00 Dropped triggers OK.
Successfully altered `test`.`su`.
查看结果新增了一个 city_id 的字段:
mysql> desc su;
+---------+------------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+---------+------------------+------+-----+-------------------+-----------------------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| c1 | int(11) | NO | | 0 | |
| c2 | int(11) | NO | | 0 | |
| c3 | int(11) | NO | | 0 | |
| c4 | int(11) | NO | | 0 | |
| c5 | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| c6 | varchar(200) | NO | | | |
| city_id | int(11) | YES | | NULL | |
+---------+------------------+------+-----+-------------------+-----------------------------+