MySQL InnoDB引擎的表通過拷貝物理文件來進行單表或指定表的復制,可以想到多種方式,今天測試其中2種:
- 將innodb引擎的表修改為Myisam引擎,然后拷貝物理文件
- 直接拷貝innodb的表空間文件(前提是獨立表空間(默認,通過show variables like 'innodb_file_per_table' 查看))進行復制
一、修改引擎
1.創建一張innodb引擎的表,並插入測試數據;
create table test_tb(id int primary key,c1 varchar(20)) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into test_tb select 1,'c1'; insert into test_tb select 2,'c2';
2. 修改引擎
alter table test_tb engine=myisam; show create table test_tb\G
3. 將物理文件拷貝至目標庫
cd /data/mysql/mysql3307/data/ cd testdb ll cd ../testdb2/ pwd ll cp ../testdb/test_tb.* . ll
4.修改權限
chown -R mysql:mysql .
5. 查看結果
記錄和源庫一致。
6. 將源庫及目標庫的表引擎修改為innodb
alter table testdb.test_tb engine=innodb; alter table testdb2.test_tb engine=innodb;
二、拷貝.idb物理表空間文件
1. 創建一張innodb的表,為了測試大表的情況,我創建了一張800W記錄的表,占用940M空間
/*先創建快速生成連續數的表及存儲過程*/ -- 建表 CREATE TABLE `test_tb2` ( `id` int(11) DEFAULT NULL, `aa` varchar(20) DEFAULT NULL, `bb` varchar(20) DEFAULT NULL, `cc` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --創建過程 DELIMITER $$ CREATE PROCEDURE `sp_test_tb2`(cnt INT ) BEGIN DECLARE i INT DEFAULT 1; TRUNCATE TABLE test_tb2; INSERT INTO test_tb2 SELECT concat(i,'a'),concat(i,'b'),concat(i,'c') ; WHILE i < cnt DO BEGIN INSERT INTO test_tb2 SELECT id + i,concat(id+i,'a'),concat(id+i,'b'),concat(id+i,'c') FROM test_tb2 WHERE id + i<=cnt; SET i = i*2; END; END WHILE; END$$ DELIMITER ; -- 生成8000000條記錄 call sp_test_tb2(8000000); select count(*) from test_tb2;
2. 在目標庫創建相同的表名
mysql> use testdb2; CREATE TABLE `test_tb2` ( `id` int(11) DEFAULT NULL, `aa` varchar(20) DEFAULT NULL, `bb` varchar(20) DEFAULT NULL, `cc` varchar(20) DEFAULT NULL, ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
3. 刪除目標表的表空間
alter table test_tb2 discard tablespace;
此時目標庫的test_tb2表近剩下數據定義文件,表空間文件已刪除
4. 拷貝源庫的idb文件
/** 需先flush table */ flush table test_tb2 for export ;
之后拷貝(會生成一個cfg文件 也一並拷貝過去)
拷貝完成后需解鎖test_tb2表
unlock tables;
5. 修改表空間文件權限
6. 目標表導入表空間數據(記錄較多的時候需要一點時間)
alter table test_tb2 import tablespace;
7. 查看導入結果
結果與源表一致
Tips:
以上2種處理方式都需要源表無寫入更新等操作下進行,且需要flush tables 將數據刷新到物理磁盤的文件上。所以建議先鎖表或停止業務,待拷貝文件后再恢復寫入等操作。
耿小廚已開通個人微信公眾號,想進一步溝通或想了解其他文章的同學可以關注我