如何修复MySQL 主从不一致的数据,让他们保持一致性呢。
1.修复前提
表需要有唯一索引。
2.创建表,保存从库信息。
CREATE TABLE ptdb.dsns (
id int(11) NOT NULL AUTO_INCREMENT,
parent_id int(11) DEFAULT NULL,
dsn varchar(255) NOT NULL,
PRIMARY KEY (id)
);
INSERT INTO ptdb.dsns(dsn) VALUES ("h=192.168.1.58,P=3306,u=root,p=rootroot");
commit;
3.修复表
修复前主库:
mysql> select *from test1;
+------+------+
| id | name |
+------+------+
| 1 | xsq1 |
| 2 | xsq2 |
| 3 | xsq3 |
| 4 | xsq4 |
+------+------+
修复前从库:
mysql> select * from test1;
+------+-------+
| id | name |
+------+-------+
| 1 | xsq1 |
| 2 | xsq2 |
| 3 | xsq3 |
| 4 | xsq44 | --不一致。
+------+-------+
4 rows in set (0.00 sec)
4.输出修复的语句。
[root@mysql1 ~]# pt-table-sync --replicate=ptdb.checksums h=192.168.1.51,u=root,p=rootroot h=192.168.1.58,u=root,p=rootroot --print --databases=test
REPLACE INTO `test`.`test1`(`id`, `name`) VALUES ('4', 'xsq4') /*percona-toolkit src_db:test src_tbl:test1 src_dsn:h=192.168.1.51,p=...,u=root dst_db:test dst_tbl:test1 dst_dsn:h=192.168.1.58,p=...,u=root lock:1 transaction:1 changing_src:ptdb.checksums replicate:ptdb.checksums bidirectional:0 pid:39850 user:root host:mysql1*/;
5.在主库上执行修复:
pt-table-sync --replicate=ptdb.checksums h=192.168.1.51,u=root,p=rootroot --databases=test --tables=test1 --charset=utf8 --execute
修复后:从库检查。
mysql> select * from test1;
+------+------+
| id | name |
+------+------+
| 1 | xsq1 |
| 2 | xsq2 |
| 3 | xsq3 |
| 4 | xsq4 | 从库原来是:xsq44,现在变成了xsq4,和主库保持一致了。
+------+------+
4 rows in set (0.01 sec)
6.总结
pt-table-sync 是个非常使用的主从数据修复工具。特别是当发现主从不一致且不想全库同步时,可以使用它进行修复。