[英]Insert row from one table to another table, which has extra column?
I am working on migration of data from one db1 to another db2. 我正在将数据从一个db1迁移到另一个db2。
I have one scenario, where table Person is present in both databases(db1 and db2). 我有一种情况,两个数据库(db1和db2)中都存在表Person。
But the table in db2 has one extra column. 但是db2中的表有一个额外的列。 Which is best effective way to write the query to migrate data from db1 Person to db2 Person. 这是编写查询以将数据从db1 Person迁移到db2 Person的最有效方法。
I have written as below, is this is the best way to write it? 我写的如下,这是最好的写法吗? Because if i have more columns and only one extra column, due to which i need to mention all the column names in loop statement. 因为如果我有更多列并且只有一个额外的列,由于这个原因,我需要在循环语句中提及所有列名。
$select = $dbh1->prepare("SELECT * FROM person");
$insert = $dbh2->prepare("INSERT INTO PERSON VALUES (?,?,?,?,?)");
$select->execute;
while ( my($PR_ID,$NAME,$LASTNAME) = $select->fetchrow_array )
{
$insert->execute($PR_ID,$NAME,$LASTNAME,'NULL','NULL');
}
如果源表和目标表中的列不匹配,请使用以下语法-
insert into table1(col1,col2,col3) select col1,col2,col3 from table2;
Zafar's answer is probably the best and quickest way to do this. Zafar的答案可能是做到这一点的最好,最快的方法。
But if you do want to do this row by row, one general rule for database access in a script is: never access a column without explicitly naming it. 但是,如果您确实希望逐行执行此操作,则脚本中数据库访问的一个一般规则是: 切勿在未明确命名的情况下访问列。 So: 所以:
SELECT *
没有SELECT *
INSERT INTO table_name VALUES (...)
否INSERT INTO table_name VALUES (...)
A corrected version of your script, guessing the column names: 脚本的更正版本,猜测列名称:
my $select = $dbh1->prepare("SELECT pr_id, name, lastname FROM person");
my $insert = $dbh2->prepare("INSERT INTO PERSON(pr_id, name, last_name) VALUES (?,?,?)");
$select->execute;
while ( my($PR_ID,$NAME,$LASTNAME) = $select->fetchrow_array )
{
$insert->execute($PR_ID,$NAME,$LASTNAME);
}
(Note that you don't need to specify the extra columns in the new table, as long as they are nullable, and you want the value to be NULL. If you do want to insert a NULL yourself, don't use 'NULL'
, but use undef
, like ikegami says.) (请注意,您不需要在新表中指定多余的列,只要它们可以为空,并且您希望该值为NULL即可。如果您自己想插入NULL,请不要使用'NULL'
,但请使用ikegami所说的undef
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.