MySQL有一个OPTIMIZE TABLE命令,可以用来回收MySQL安装中未使用的空间。是否有一种方法(内置命令或通用存储过程)可以为数据库和/或服务器安装中的每个表运行这种优化,还是必须自己编写脚本?


当前回答

我的建议是:从碎片率最高的表开始

for table in `mysql -sss -e "select concat(table_schema,".",table_name) from information_schema.tables where table_schema not in ('mysql','information_schema','performance_schema') order by data_free desc;"
do
mysql -e "OPTIMIZE TABLE $table;"
done

其他回答

这个bash脚本将接受根密码作为选项,并逐个优化它,并输出状态:

#!/bin/bash

if [ -z "$1" ] ; then
  echo
  echo "ERROR: root password Parameter missing."
  exit
fi
MYSQL_USER=root
MYSQL_PASS=$1
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
TBLLIST=""
COMMA=""
SQL="SELECT CONCAT(table_schema,'.',table_name) FROM information_schema.tables WHERE"
SQL="${SQL} table_schema NOT IN ('information_schema','mysql','performance_schema')"
for DBTB in `mysql ${MYSQL_CONN} -ANe"${SQL}"`
do
    echo OPTIMIZE TABLE "${DBTB};"
    SQL="OPTIMIZE TABLE ${DBTB};"
    mysql ${MYSQL_CONN} -ANe"${SQL}"
done

下面的示例php脚本可以帮助您优化数据库中的所有表

<?php

dbConnect();

$alltables = mysql_query("SHOW TABLES");

while ($table = mysql_fetch_assoc($alltables))
{
   foreach ($table as $db => $tablename)
   {
       mysql_query("OPTIMIZE TABLE '".$tablename."'")
       or die(mysql_error());

   }
}

?>

MySQL管理员(MySQL GUI工具的一部分)可以在数据库级别为你做这些。

只需选择您的模式并按下右下角的Maintenance按钮。

由于GUI工具已经达到了生命结束的状态,他们很难在mysql页面上找到。通过谷歌:http://dev.mysql.com/downloads/gui-tools/5.0.html找到他们

我不知道新的MySQL Workbench是否也能做到这一点。

您可以使用mysqlcheck命令行工具,它也应该能够做到这一点。

从命令行:

mysqlcheck -o <db_name> -u<username> -p

然后输入密码

使用mysql客户端可以对数据库中的所有表进行优化/检查和修复。

首先,你应该得到所有的表列表,用','分隔:

mysql -u[USERNAME] -p[PASSWORD] -Bse 'show tables' [DB_NAME]|xargs|perl -pe 's/ /,/g'

现在,当你有所有要优化的表列表时:

mysql -u[USERNAME] -p[PASSWORD] -Bse 'optimize tables [tables list]' [DB_NAME]