从旧表导入到具有不同结构的新表中

时间:2013-11-07 08:58:51

标签: mysql import

我的旧桌子有大约600列。我们称这个表为old_table

我的新表有603列。我们称这个表为new_table

现在要将数据从old_table导入new_table,我尝试按照以下方法:

$q = mysql_query("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS 
              WHERE TABLE_SCHEMA = 'databasename' AND TABLE_NAME = 'old_table'");

$cols = array();
while($r = mysql_fetch_array($q))
{   
   $cols[] = $r['COLUMN_NAME'];     
}

$sql = "INSERT INTO new_table ";
$sql .= "SELECT ";
$sql .= implode(", ", $cols);
$sql .= " FROM old_table";

mysql_query($sql) or die("Something went wrong: ".mysql_error());

但这导致 Column count doesn't match value count at row 1 ,因为该查询还考虑了new_table的3个新列。

我有没有办法让它跳过new_table中的其他列并插入old_table的所有数据?

1 个答案:

答案 0 :(得分:1)

是。您可以为新列提供默认值并将其添加到insert语句中,也可以为要插入的列命名。

$sql = "INSERT INTO new_table ";
$sql .= "SELECT ";
$sql .= implode(", ", $cols);
$sql .= ", value_for_new_column_1";
$sql .= ", value_for_new_column_2";
$sql .= ", value_for_new_column_3";
$sql .= " FROM old_table";

$sql = "INSERT INTO new_table ";
$sql .= "(" . implode(", ", $cols) . ")";
$sql .= "SELECT ";
$sql .= implode(", ", $cols);
$sql .= " FROM old_table";