Perl と DBI を使用して MySQL でクエリを実行し、結果を別のテーブルに挿入する必要があります。2 番目のテーブルはその場で作成され、元のクエリで返されたのと同じ数のフィールドに加えて、もう 1 つのフィールドが定義されます。
最初のクエリや、返されるフィールドの数を事前に知る方法はありません。だから私はこの非常に醜いことをしています(要約):
# 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
は実際の準備されたステートメントなので... とにかくそれを使用して、レコードごとにPerlに渡すことなく、そのステートメントの結果を別のテーブルに挿入するようにMySQLに指示することはありますか?
コメントありがとうございます。
フランシスコ