歪麦博客

mysqldiff实现MySQL数据表比较

本文介绍mysqldiff工具来比较数据表结构,并生成差异SQL语句。

mysqldiff类似Linux下的diff命令,用来比较对象的定义是否相同,并显示不同的地方。

如果要比较数据库是否一致,可以用另外一个工具:mysqldbcompare点击查看教程)。

以下是mysqldiff的用法。

1 安装

mysqldiff是MySQL Utilities中的一个脚本,默认的MySQL不包含这个工具集,所以需要独立安装。

Linux系统在下载页面选择对应发行版。

2 语法

mysqldiff的语法格式是:

$ mysqldiff --server1=user:pass@host:port:socket --server2=user:pass@host:port:socket db1.object1:db2.object1 db3:db4

这个语法有两个用法:

接下来看一些主要的参数:

3 范例

先创建两个表。

use study;

create table test1(
    id int not null primary key,
    a varchar(10) not null,
    b varchar(10),
    c varchar(10) comment 'c',
    d int
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='test1';

create table test2(
    id int not null,
    a varchar(10),
    b varchar(5),
    c varchar(10),
    D int
)ENGINE=myisam DEFAULT CHARSET=utf8 COMMENT='test2';

不使用--skip-table-options

mysqldiff --server1=root:root@localhost --server2=root:root@localhost --changes-for=server2 --show-reverse --difftype=sql study.test1:study.test2

使用--skip-table-options

如果需要生成SQL文件,加上输出就可以了:

mysqldiff --server1=root:root@localhost --server2=root:root@localhost --changes-for=server2 --show-reverse --difftype=sql study.test1:study.test2 > output.sql

说明:执行MySQL语句时可能会遇到这样错误:Error 1054 – Unknown column ‘name’ in ‘aspect’

这是因为mysqldbcompare生成的ALTER语句中,用逗号,拼装了多条ADDCHANGE等语句,如果这些语句还包含AFTER关键字,就会提示这个错误并中断执行MySQL语句。解决的办法就是:去除AFTER及其后面的条件

这可能是MySQL的一个Bug,详情参考:http://bugs.mysql.com/bug.php?id=34972 和 http://bugs.mysql.com/bug.php?id=60650

 

参考资料:

  1. MySQL 对比数据库表结构
  2. mysqldiff — Identify Differences Among Database Objects
  3. MySQL管理工具MySQL Utilities — mysqldiff(11)
退出移动版