1. 程式人生 > >釋放已刪除的InnoDB磁碟空間

釋放已刪除的InnoDB磁碟空間

Innodb資料庫對於已經刪除的資料只是標記為刪除,並不真正釋放所佔用的磁碟空間,這就導致InnoDB資料庫檔案不斷增長。如果想徹底釋放這些已經刪除的資料,需要把資料庫匯出,刪除InnoDB資料庫檔案,然後再倒入。 下面是基本的步驟: 

1 使用mysqldump命令將InnoDB資料庫匯出

2 停止MySQL

3 刪除所有InnoDB資料庫檔案和日誌

4 啟動MySQL並自動重建InnoDB資料庫檔案和日誌檔案

5 匯入前面備份的資料庫檔案

具體命令:

# 備份資料庫:

mysqldump -uroot -proot --quick --force --all-databases > mysqldump.sql

# 停止資料庫

service mysqld stop
# 刪除這些大檔案
rm /usr/local/mysql/var/ibdata1
rm /usr/local/mysql/var/ib_logfile*

# 手動刪除除Mysql之外所有資料庫資料夾,然後啟動資料庫

service mysqld start

# 還原資料

mysql -uroot -proot < mysqldump.sql
還有一種方式是在建立資料庫的時候設定innodb_file_per_table,這樣InnoDB會對每個表建立一個數據檔案,然後只需要執行OPTIMIZE TABLE 命令就可以釋放所有已經刪除的磁碟空間。

編輯my.ini或my.cnf 在innodb段中加入 innodb_file_per_table=1 # 1為啟用,0為禁用

通過mysql語句可以檢視該變數的值:

mysql> show variables like '%per_table%';