Linux 技术手札

MySQL 开启 innodb_file_per_table 及转换现有资料表

MySQL 会将 InnoDB 的资料表内的资料及索引全部储存到共享空间, 即是所有 InnoDB 资料表的资料全都放到 ibdata1 档案内。而 innodb_file_per_table 就可以设定每个资料表, 使用独立表空间储存资料, 即是每个资料表有属于自己的 .ibd 档案。

这样做的好处是对日后的管理较容易, 在 MySQL 5.6.6 开始, innodb_file_per_table 默认是开启, 而在 5.6.6 前的版本默认是关闭的, 要查询目前 MySQL 的 innodb_file_per_table 是否开启, 可以查看 MySQL 的 innodb_file_per_table 变量:

以下是开启 innodb_file_per_table, 及将现有储存在共享空间 (ibdata1) 的资料表, 转换到 innodb_file_per_table 的步骤。

1. 关闭 MySQL:

# systemctl stop mysql

2. 将 MySQL 数据库目录完整备份, 即使出错也可以即时修复:

# cp -ra /var/lib/mysql mysqldata.backup

3. 编辑 my.cnf:

要开启 innodb_file_per_table, 先开启 my.cnf:

# vi my.cnf

在 [mysqld] 段落加入以下一行:

innodb_file_per_table=1

4. 启动 MySQL:

# systemctl start mysql

5. 转换资料表

这时执行中的 MySQL 已经开启了 innodb_file_per_table, 所有新建立的 InnoDB 资料表都会使用独立空间, 即使用属于自己的 .ibd 档, 但原有的 InnoDB 资料表则仍旧使用共享空间 (ibdata1), 要转换除了用 mysqldump 汇出资料表, 将资料表删除及重新汇入外, 也可以用 ALTER TABLE 指令完成, 登入 MySQL CLI 或 phpMyAdmin, 例如旧有 InnoDB 资料表名称是 table_name, 执行以下 SQL 指令:

ALTER TABLE table_name ENGINE=InnoDB;

这样 table_name 资料表便会转换到使用独立空间表。

Exit mobile version