在MySQL中复制数据库,如何复制视图?

7

我正在尝试使用运行在MySQL服务器上的PHP脚本,在一个新的数据库中复制一个数据库。目前为止,我所拥有的代码如下:

$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"; 
        }
    }
}

目前这个程序会查找$old_news中的所有表,通过information_schema找到表类型,并在$new_news中创建一个相同类型的表。对于表格,它会创建相同的表结构,然后使用“INSERT INTO SELECT”来填充它们。

如何在不使用mysqldump备份整个数据库的情况下复制视图?

3个回答

5

2

0
以下代码适用于我。它将从源数据库复制所有视图到目标数据库。
$link = mysql_connect('hostname', 'user', 'password',false,128) or die(mysql_error());
mysql_select_db('source_database') or die(mysql_error());

$qry=mysql_query("SHOW FULL TABLES IN source_database WHERE TABLE_TYPE LIKE 'VIEW'");

while ($rows= mysql_fetch_object($qry)){
        $view_name=$rows->Tables_in_techdb_beta;
        $select_view=mysql_query("SHOW CREATE VIEW ".$view_name);
        while ($view_rows= mysql_fetch_object($select_view)){
            foreach($view_rows as $key=>$val){
                if ($key=='Create View'){
                    $views_array[]=$val;
                }
            }
        }
}
//echo "<pre>"; print_r($views_array);
$link2 = mysql_connect('hostname', 'user', 'password',false,128) or die(mysql_error());
mysql_select_db('target_database') or die(mysql_error());
ini_set('MAX_EXECUTION_TIME', -1);
foreach($views_array as $key => $val){
    $sql=trim($val);
    mysql_query($sql);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接