在生產環境中,單表或多表的備份與還原是常見需求。對於 InnoDB 引擎,傳統方式需整庫恢復,但自 MySQL 5.6.6 起引入的 Transportable Tablespace(表空間傳輸) 特性,使得單表跨實例遷移成為可能。本文詳細解析該技術的原理、限制與實戰操作流程。
innodb_file_per_table=ON(5.6.6+ 預設開啟),系統表空間中的表不支援foreign_key_checks)lower_case_table_names=1表空間傳輸的核心流程包含三個關鍵階段:
.cfg 元數據文件(含空間 ID、LSN 等關鍵信息)日誌示例:
[Note] InnoDB: Sync to disk of "test"."ttlsa" started.
[Note] InnoDB: Stopping purge
[Note] InnoDB: Writing table metadata to './test/ttlsa.cfg'
[Note] InnoDB: Table "test"."ttlsa" flushed to disk
.cfg 文件自動刪除日誌示例:
[Note] InnoDB: Importing tablespace for table 'test/ttlsa' that was exported from host 'ubuntu'
[Note] InnoDB: Phase I - Update all pages
[Note] InnoDB: Sync to disk
[Note] InnoDB: Phase III - Flush changes to disk
[Note] InnoDB: Phase IV - Flush complete
假設源實例為 server_A,目標實例為 server_B,操作表 test.ttlsa。
-- server_B
USE test;
CREATE TABLE ttlsa (id INT) ENGINE=InnoDB;
ALTER TABLE ttlsa DISCARD TABLESPACE;
-- server_A
USE test;
FLUSH TABLES ttlsa FOR EXPORT;
-- ⚠️ 會話不可退出,否則 .cfg 文件會消失
# 在 server_A 執行,必須在 UNLOCK TABLES 前完成
scp /path/to/datadir/test/ttlsa.{ibd,cfg} destination-server:/path/to/datadir/test
-- server_A
USE test;
UNLOCK TABLES;
-- server_B
USE test;
ALTER TABLE ttlsa IMPORT TABLESPACE;
.cfg 文件雖非強制,但缺失時無法完成 Schema 驗證,僅建議在結構確定一致或災難恢復場景下忽略innodb_file_per_table=1lower_case_table_names表空間傳輸技術為 InnoDB 單表遷移提供了原生級解決方案,掌握其內部機制有助於在生產環境中安全、高效地完成表級數據移動與恢復。