Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying a database in MySQL, how to copy views?

Trying to copy a database into a new database, using a PHP script that runs SQL queries on a MySQL server. The code I have sofar is:

$dbh->exec("CREATE DATABASE IF NOT EXISTS $new_news CHARACTER SET UTF8;");
$results = $dbh->query("SHOW TABLES FROM $old_news");
$table_list = $results->fetchAll(PDO::FETCH_NUM);

foreach($table_list as $table_row){
    foreach($table_row as $table){
        $results = $dbh->query("SELECT table_type FROM information_schema.tables where table_schema = '$old_news' and table_name = '$table'");
        $table_type = $results->fetch(PDO::FETCH_ASSOC);
        $table_type = $table_type['table_type'];
        if($table_type == 'BASE TABLE'){
            echo "Creating table $table and populating...\n";
            $dbh->exec("CREATE TABLE $new_news.$table LIKE $old_news.$table");
            $dbh->exec("INSERT INTO $new_news.$table SELECT * FROM $old_news.$table");
        }else if($table_type == 'VIEW'){
            //echo "Creating view $table...\n";
            //$dbh->exec("CREATE VIEW $new_news.$table LIKE $old_news.$table");
            echo "$table is a view, which cannot be copied atm\n";  
        }else{
            echo "Skipping $table_type $table, unsupported type\n"; 
        }
    }
}

This currently looks at all tables in $old_news, finds the table type in the information_schema, and creates an identical table in $new_news depending on the type. For tables, it creates the table structure the same, then 'INSERT INTO SELECT' to fill them.

How do you copy a view without mysqldump the entire database?

like image 935
Ripptor Avatar asked Aug 10 '11 15:08

Ripptor


1 Answers

You can use INFORMATION_SCHEMA.VIEWS to see the view definition, or SHOW CREATE VIEW for the whole statement.

like image 178
Matthew Flaschen Avatar answered Oct 12 '22 22:10

Matthew Flaschen