How to copy a table from one mysql database to another mysql database

前端 未结 12 1438
一个人的身影
一个人的身影 2020-12-07 21:03

I need to copy a table from one database to another. This will be a cronjob. Which one is the best way to do it? PHP script or Shell Script. The problem with PHP, both datab

相关标签:
12条回答
  • 2020-12-07 21:29
    CREATE TABLE db_target.cloned_table 
    SELECT * 
    FROM db_source.source_table;
    
    0 讨论(0)
  • 2020-12-07 21:33

    One liner with different servers

    mysqldump -h host1 -u user1 -ppassword1 databasename TblName | mysql -h host2 -u user2 -ppassword2 anotherDatabase
    
    0 讨论(0)
  • 2020-12-07 21:33
    $L1 = mysql_connect('localhost', 'user1', 'pass1');
    $DB1 = mysql_select_db('database1', $L1);   
    
    $L2 = mysql_connect('localhost', 'user2', 'pass2');
    $DB2 = mysql_select_db('database2', $L2);   
    
    $re=mysql_query("SELECT * FROM table1",$L1);
    while($i=mysql_fetch_assoc($re))
    {
        $u=array();
        foreach($i as $k=>$v) if($k!=$keyfield) $u[]="$k='$v'";
        mysql_query("INSERT INTO table2 (".implode(',',array_keys($i)).") VALUES ('".implode("','",$i)."') ON DUPLICATE KEY UPDATE ".implode(',',$u),$L2) or die(mysql_error());
    }
    

    user1, pass1, database1, table1 reffers to initial table user2, pass2, database2, table2 reffers to copied table $keyfield is the primary key of table

    0 讨论(0)
  • use <from database>

    create table <to database.new name> as (select * from <table to copy>);
    
    0 讨论(0)
  • 2020-12-07 21:34

    I'd dump it. Much less complicated than anything PHP based.

    mysqldump -u user1 -ppassword1 databasename > dump.sql
    mysql -u user2 -ppassword2 databasename < dump.sql
    

    MySQL reference: 4.5.4. mysqldump — A Database Backup Program

    0 讨论(0)
  • 2020-12-07 21:41
    mysqldump -u user1 -ppassword1 databasename TblName | mysql -u user2 -ppassword2 anotherDatabase
    

    It all can be done in a single command.

    0 讨论(0)
提交回复
热议问题