2011-08-09 73 views
2

我想從一個數據庫中獲取表並將此數據追加到另一個數據庫中的表中。但是,他們有相似的數字(包括id),需要更新才能被複制。有沒有可以自動執行此操作的功能?或者我需要在兩者之間編寫腳本?如何將一個mysql表追加到另一個數據庫中的另一個表中

到目前爲止我有:

#!/bin/sh 
mysqldump -uuser1 -ppw1 database1 table1 > /home/user/public_html/database1.sql --skip-add-drop-table --skip-create-options 
mysql -uuser2 -ppw2 database2 < /home/user/public_html/database1.sql 
rm /home/user/public_html/database1.sql 
+1

都是坐在同一臺服務器上的數據庫嗎?你是否試圖將數據從一個表追加到另一個表? – ajreal

+0

是的,他們都坐在同一臺服務器上。是的,試圖將數據從一個表追加到另一個表中,在另一個數據庫(相同的服務器)中 – Ruben

回答

1

聽起來似乎會安全很多通過腳本,這似乎是很簡單的事情 - 只抓住從第一DB中的數據,並執行批量插入到另一方面,讓MySQL處理ID本身。這應該在任何下降腳本語言中大約需要10-30 LOC,並且可以讓您更好地控制結果。

6

您可以從一個表中選擇並將其插入另一個表中。結果將被「附加」到原始數據中。

insert into new_table (id, name) select old_id, old_name from old_table; 

從一個數據庫從其他數據庫

insert into new_database.new_table (id, name) select old_id, old_name from old_database.old_table; 
+2

該查詢假定舊ID和新ID不衝突。如果不是這種情況,只需從查詢中刪除ID字段。 –

+0

這是不是假設兩個表都在同一個數據庫中? (實際的目標是從一個新數據庫中的一個新表中獲取來自不同數據庫的許多表) – Ruben

+1

insert into new_database.new_table(id,name)從old_database.old_table中選擇old_id,old_name; –

0

我通過創建,致力於爲每一個新的數據庫新連接PHP腳本解決它附加一個表的表。此腳本首先清空主表,然後再附加其他表的數據。具有NULL上的第一個條目並且$ row [x]從1開始可確保它追加。不知道它是否是最好的解決方案,但它可以工作。

<?php 

$db_user = "database_all_usr"; 
$db_pw = ""; 
$db_database = "database_all_db"; 

mysql_connect("localhost", $db_user, $db_pw) or die(mysql_error()); 
mysql_select_db($db_database) or die(mysql_error()); 

$sql = "TRUNCATE TABLE table_all"; 
mysql_query($sql) or die(mysql_error()); 

copy_table("database1_db","database1_usr","",$db_database,$db_user,$db_pw); 
copy_table("database2_db","database2_usr","",$db_database,$db_user,$db_pw); 

function copy_table($db_current,$db_user_current,$db_pw_current,$db_host,$db_user_host,$db_pw_host){ 

    mysql_connect("localhost", $db_user_current, $db_pw_current) or die(mysql_error()); 
    mysql_select_db($db_current) or die(mysql_error()); 

    $sql = "SELECT * FROM table"; 

    $result = mysql_query($sql) or die(mysql_error()); 

    mysql_connect("localhost", $db_user_host, $db_pw_host) or die(mysql_error()); 
    mysql_select_db($db_host) or die(mysql_error()); 

    while ($row = mysql_fetch_row($result)) { 

     $sql = "INSERT INTO table_all VALUES (NULL, '$row[1]', '$row[2]')"; //adapt to the amount of columns 
     mysql_query($sql) or die(mysql_error()); 
    } 
} 
?> 
相關問題