我需要使用 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?
提前感谢您的评论。
弗朗西斯科