【问题标题】:Use executed statement to insert results in another table (Perl DBI and MySQL)使用执行语句将结果插入另一个表(Perl DBI 和 MySQL)
【发布时间】: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。

弗朗西斯科

【问题讨论】:

    标签: mysql perl dbi dbd


    【解决方案1】:

    这个答案实际上来自@eggyal(作为评论留下),但后来他删除了答案,再也没有回来。

    无论如何,我想分享他的答案,因为它非常有用。也许有些事情太简单了,但我只是不知道我可以这样做:

    create table `new_table` select * from `other_table`
    

    我什至可以这样做:

    create table `new_table` select SQL_CALC_FOUND_ROWS * from `other_table` limit 50;
    select found_rows();
    

    这简直太棒了!

    速度很好,我什至不用担心字段数据类型,MySQL会根据传递的查询自动完成。

    @eggyal:如果您再次访问此帖子,请随时添加您的答案,我会选择它。感谢您的评论!

    弗朗西斯科

    【讨论】:

      【解决方案2】:

      如果您不想指定每个字段,可以使用如下语句:

      • CREATE TABLE newtable LIKE oldtable(并可能在此之后使用 ALTER TABLE 添加新字段)
      • INSERT INTO newtable SELECT * FROM oldtable
      • CREATE TABLE AS [$received_sql]

      【讨论】:

      • @eggyal:哇,这听起来就像我可以使用的一样。我马上试试。请添加您的答案。 :-)
      • golimar:感谢您的回答。它对我不起作用的原因是,正如我所提到的,我无法提前知道将要执行的查询,所以在得到结果之前我不知道如何创建新表(数字和类型字段)。但是,@eggyal 的评论是一个完美的解决方案,我不知道我能做到这一点。另外,我不知道他为什么删除他的评论。我很幸运能按时看到它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 2010-11-17
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      相关资源
      最近更新 更多