MySQL 原生 RENAME TABLE 僅支援單表操作,面對數十上百張表需統一變更前綴(如 old_ → new_)時,逐條執行極其低效。本文提供兩種成熟方案:純 SQL 生成腳本法與 PHP 自動化腳本法,滿足不同場景需求。
利用 information_schema.tables 配合 CONCAT 生成批量 ALTER TABLE 語句,再複製執行。
SELECT CONCAT('ALTER TABLE ', table_name, ' REPLACE TO ', REPLACE(table_name, 'old_', 'new_'), ';')
FROM information_schema.tables
WHERE table_schema = 'your_db' AND table_name LIKE 'old_%';
SELECT CONCAT('ALTER TABLE ', table_name, ' RENAME TO ', 'db_', SUBSTRING(table_name, 3), ';')
FROM information_schema.tables
WHERE table_schema = 'your_db' AND table_name LIKE 'db%';
操作步驟:
ALTER TABLE 語句。完整可執行的 PHP 腳本,支援指定舊/新前綴,自動遍歷並重命名。
<?php
// 配置區
$dbHost = 'localhost';
$dbName = 'your_db';
$dbUser = 'root';
$dbPass = 'password';
$oldPrefix = 'old_';
$newPrefix = 'new_';
$mysqli = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
if ($mysqli->connect_errno) {
die("連線失敗: " . $mysqli->connect_error);
}
// 獲取所有表名
$tables = [];
$res = $mysqli->query("SHOW TABLES");
while ($row = $res->fetch_row()) {
$tables[] = $row[0];
}
// 篩選並重命名
$renamed = 0;
foreach ($tables as $table) {
if (strpos($table, $oldPrefix) === 0) {
$newName = $newPrefix . substr($table, strlen($oldPrefix));
$sql = "RENAME TABLE `$table` TO `$newName`";
if ($mysqli->query($sql)) {
echo "✓ $table → $newName\n";
$renamed++;
} else {
echo "✗ $table 失敗: " . $mysqli->error . "\n";
}
}
}
echo "完成,共重命名 $renamed 張表。\n";
$mysqli->close();
SELECT CONCAT('DROP TABLE ', table_name, ';')
FROM information_schema.tables
WHERE table_schema = 'your_db' AND table_name LIKE 'uc_%';
ALTER、DROP、CREATE 權限。LIKE 條件需注意。掌握這兩招,表前綴批量變更不再是噩夢。