如何从MySQL数据库中删除所有空表?

lin*_*eak 9 mysql

如何从MySQL数据库中删除所有空表,只留下至少有1条记录的表?

Bil*_*win 5

使用Percona Toolkit 中的pt-find

$ pt-find --dblike "mydatabase" --empty --exec-plus "DROP TABLE %s"
Run Code Online (Sandbox Code Playgroud)


lin*_*eak 3

为了完整性还有一个 PHP 版本。它不会删除任何内容,只是为您打印 DROP 语句:

<?php
$username="root";
$password="mypassword";
$database="mydatabase";
mysql_connect('localhost',$username,$password);
mysql_select_db($database) or die( "Unable to select database");

function drop_empty_tables(){
    $tables = mysql_query('SHOW TABLES');
    while($table = mysql_fetch_array($tables)){
        $table = $table[0];
        $records = mysql_query("SELECT * FROM $table");
        if(mysql_num_rows($records) == 0){
            // mysql_query("DROP TABLE $table");
            echo "DROP TABLE $table;\n";
        }
    }
}

drop_empty_tables();
?>
Run Code Online (Sandbox Code Playgroud)