【发布时间】:2013-04-24 12:11:25
【问题描述】:
我需要使用 Perl 和 DBI 在 MySQL 中执行查询并将结果插入另一个表中。第二个表是动态创建的,用于定义与原始查询返回的字段数相同的字段,再加上一个字段。
我无法提前知道第一个查询或它将返回多少个字段。所以我在做这个非常丑陋的事情(总结):
# Execute the received query
my $sth = $dbh->prepare($received_sql);
$sth->execute;
# Get the fields names and create the new table
my @fields = @{$sth->{NAME}};
my $create_table = "...some sql and a map from @fields...";
# Start getting the results from the query one by one just to insert them into the new table
while (my @record = $sth->fetchrow_array) {
my $sql = "insert into `new_table` (";
$sql .= join ', ', map { "`$_`" } @fields;
$sql .= ") values (";
$sql .= join ', ', map { '?' } @fields;
$sql .= ')';
my $insert = $dbh->prepare($sql)
$insert->execute(@record);
}
如果我能做到这一点就完美了:
insert into `new_table` (...) select (...) from ...
但是,我需要知道从第一个查询返回的字段的名称,并在向其中插入数据之前创建相应的表。
所以,我一直在想,既然$sth 是一个实际的准备好的语句...是否有办法告诉 MySQL 将该语句的结果插入到另一个表中,而不是让它通过记录记录到 Perl?
提前感谢您的 cmets。
弗朗西斯科
【问题讨论】: