1. 程式人生 > >MySQL innodb表使用表空間物理文件復制或遷移表

MySQL innodb表使用表空間物理文件復制或遷移表

key mar table 文件 mysq 寫入 文件權限 har pri

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文件

技術分享圖片

5. 修改表空間文件權限

技術分享圖片

6. 目標表導入表空間數據(記錄較多的時候需要一點時間)

alter table test_tb2 import tablespace;

技術分享圖片

7. 查看導入結果

技術分享圖片

結果與源表一致

Tips:

以上2種處理方式都需要源表無寫入更新等操作下進行,且需要flush tables 將數據刷新到物理磁盤的文件上。所以建議先鎖表或停止業務,待拷貝文件後再恢復寫入等操作。

MySQL innodb表使用表空間物理文件復制或遷移表