LoginSignup
6
7

More than 5 years have passed since last update.

MySQLのスキーマをリネームする方法について

Posted at

MySQLでは、「RENAME DATABASE」構文がサポートされていません。
そのため、スキーマ名を変更したい場合は以下のような手順で行うことが出来ます。

1. 以下の get_rename_sql.txt を適当なところに配置
$ cat /tmp/get_rename_sql.txt  
CREATE DATABASE IF NOT EXISTS <new_schema_name>;

SELECT DISTINCT CONCAT(
'RENAME TABLE ', 
t.table_schema,'.', t.table_name, 
' TO ', 
"<new_schema_name>", '.', t.table_name, 
';' ) 
as rename_table INTO OUTFILE "/tmp/rename_<old_schema_name>_tables.sql"
FROM information_schema.tables as t WHERE t.table_schema="<old_schema_name>"
AND t.table_type = "BASE TABLE";
2. get_rename_sql.txt 内の <old_schema_name> と <new_schema_name>を目的の名前に変更
3. 以下のコマンドを実行

$ mysql -u root -p < /tmp/get_rename_sql.txt

※ /tmp/直下に、RENAME TABLE文をまとめたクエリが作られる

$ cat /tmp/get_rename_sql.txt  
RENAME TABLE old_db.t1 TO new_db.t1;
RENAME TABLE old_db.t3 TO new_db.t3;
4. 作成されたsqlファイルを実行

$ mysql -u root -p < /tmp/rename_old_db_tables.sql

これで対象スキーマのリネームが出来るはずです。なお、手順4.でRENAME TABLEを実行した後は、
旧スキーマからテーブルが無くなってしまう点には注意が必要です。

【参考URL】
http://qiita.com/tuboc/items/06add22b692a25bd19b5

=========================================================

【補足】「VIEW」はスキーマを跨いでのRENAME TABLEが実行できません。

http://stackoverflow.com/questions/5475473/how-to-rename-a-view-in-mysql

If it's within the same database, it's OK, but contrary to tables,
MySQL does not support moving views from one database to another.
Thus, DROP+CREATE is a more general approach.

そのため、VIEWに関しては以下のようにmysqldumpを使った方法を推奨します。

1. 以下のコマンドで、VIEWのテーブル名のみを抽出(半角スペース区切り)
$ mysql -u root -sN -p -e "SELECT GROUP_CONCAT( DISTINCT t.table_name SEPARATOR ' ' ) \
FROM information_schema.tables as t WHERE t.table_schema='book' AND t.table_type='VIEW';"
Enter password: 
test_view test_view2   # VIEWのテーブル名が出力される
2. VIEWのみのdumpファイルを出力

$ mysqldump -u root -p <old_schema> test_view test_view2 > /tmp/rename_<old_schema>_views.sql

3. 新スキーマにdumpファイルをインポート

$ mysql -u root -p <new_schema> < /tmp/rename_<old_schema>_views.sql

ちなみに、新スキーマにテーブルがないとVIEWの作成が出来ないので、
上記の手順は冒頭のスキーマのリネームが完了してから行って下さい。

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7