How do I quickly rename a MySQL database (change schema name)?

前端 未结 30 2415
余生分开走
余生分开走 2020-11-22 14:54

The MySQL manual at MySQL covers this.

Usually I just dump the database and reimport it with a new name. This is not an option for very big databases. Apparently

30条回答
  •  情歌与酒
    2020-11-22 15:26

    You can use SQL to generate an SQL script to transfer each table in your source database to the destination database.

    You must create the destination database before running the script generated from the command.

    You can use either of these two scripts (I originally suggested the former and someone "improved" my answer to use GROUP_CONCAT. Take your pick, but I prefer the original):

    SELECT CONCAT('RENAME TABLE $1.', table_name, ' TO $2.', table_name, '; ')
    FROM information_schema.TABLES 
    WHERE table_schema='$1';
    

    or

    SELECT GROUP_CONCAT('RENAME TABLE $1.', table_name, ' TO $2.', table_name SEPARATOR '; ')
    FROM information_schema.TABLES 
    WHERE table_schema='$1';
    

    ($1 and $2 are source and target respectively)

    This will generate a SQL command that you'll have to then run.

    Note that GROUP_CONCAT has a default length limit that may be exceeded for databases with a large number of tables. You can alter that limit by running SET SESSION group_concat_max_len = 100000000; (or some other large number).

提交回复
热议问题