您的位置:首页 > 数据库 > MySQL

每日MySQL之025:InnoDB,直接拷贝文件来实现表的复制

2017-08-14 22:56 471 查看
对于InnoDB 来讲,可以使每个表使用单独的表空间,也就是每个表都有自己的文件,称为File-Per-Table。 可以利用这个特点,直接拷贝对应文件,把表复制到另外一个MySQL实例下, 又被称为 Transportable Tablespace。

假设有两个MySQL实例,一个运行在db2a(源端)下,另一个运行在db2b(目标端)下,现在演示一下,如何通过这种方式将db2a下的表复制到db2b下:

1. db2a上创建一张表,并插入数据

mysql> use test1;

mysql> create table t(c1 INT) ENGINE=InnoDB;

mysql> insert into t values(2),(3),(5),(7),(11);

2. db2b上也创建相同的表

mysql> USE test1;

mysql> CREATE TABLE t(c1 INT) ENGINE=InnoDB;

3. db2b上, discard 掉现有的表空间

mysql> ALTER TABLE t DISCARD TABLESPACE;

4. db2a上,运行FLUSH TABLES ... FOR EXPORT命令:

mysql> FLUSH TABLES t FOR EXPORT;

在数据库目录下,可以看到多出一个cfg文件:

root@db2a:/var/lib/mysql/test1# ls t.*

t.cfg t.frm t.ibd

5. 将 .ibd 文件和 .cfg metadata 文件从db2a上拷贝到db2b上:

root@db2a:/var/lib/mysql/test1# scp t.{cfg,ibd} db2b:/var/lib/mysql/test1

t.cfg 100% 355 0.4KB/s 00:00

t.ibd 100% 96KB 96.0KB/s 00:00

6. db2a上,使用UNLOCAL TABLES释放FLUSH TABLES ... FOR EXPORT命令获取的锁

mysql> UNLOCK TABLES;

7. db2b上,导入从db2a上复制过来的表空间:

mysql> alter table t import tablespace;

Query OK, 0 rows affected (0.45 sec)

mysql> select * from t;

+------+

| c1 |

+------+

| 2 |

| 3 |

| 5 |

| 7 |

| 11 |

+------+

5 rows in set (0.00 sec)

报错与说明,db2b上第一次import tablespace的时候,报表空间不存在

mysql> alter table t import tablespace;
ERROR 1812 (HY000): Tablespace is missing for table `test1`.`t`.

经检查,发现对应文件的owner和group为root,实际上应该均为mysql,修改之后,导入正常

root@db2b:/var/lib/mysql/test1# ll t.*

-rw-r----- 1 root root 355 Aug 14 05:48 t.cfg

-rw-r----- 1 mysql mysql 8556 Aug 14 05:47 t.frm

-rw-r----- 1 root root 98304 Aug 14 05:48 t.ibd

root@db2b:/var/lib/mysql/test1# chown mysql:mysql t.*

参考资料:
https://dev.mysql.com/doc/refman/5.7/en/tablespace-copying.html https://dev.mysql.com/doc/refman/5.7/en/tablespace-copying.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息