Perl DBI MySQL 使用占位符和外键插入

Perl DBI MySQL Insert with both placeholders and foreign key

我对 MySQL Perl DBI 有点困惑。我已经搜索过了,一次只能找到一半的答案,我不知道如何结合我所知道的来得到正确的答案。

我有几个数据库,一个是父数据库:

mysql> desc records;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| File_Id  | int(11)     | NO   | PRI | NULL    | auto_increment |
| fname    | varchar(59) | YES  |     | NULL    |                |
| type     | varchar(3)  | YES  |     | NULL    |                |
| n1size   | int(11)     | YES  |     | NULL    |                |
| downdate | date        | YES  |     | NULL    |               

mysql> desc mhqc;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| MQ_Id    | int(11)     | NO   | PRI | NULL    | auto_increment |
| fieldnum | tinyint(4)  | YES  |     | NULL    |                |
| result   | varchar(10) | YES  |     | NULL    |                |
| File_Id  | int(11)     | YES  | MUL | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

记录已经填好,我想在mhqc中添加记录。我把我的 SQL 声明搞得一团糟!

我需要插入的变量(为简单起见而简单定义)是:

my @fields = (1..41);  # this is for the fieldname column
my @results # 41 elements, contains results of checks performed on the fields 1-41

所以,我想遍历 results/fields:

INSERT INTO mphqc (MQ_Id, fieldname, result, File_Id) values (NULL, ?, ? ... 

... 在这里我卡住了。我显然需要包含某种 select 声明,如下所示,以将所有内容联系在一起

SELECT File_Id from records where fname = \'$in_file';

当需要在子 table 中记录 File_Id 时,我找不到如何同时执行这两项操作。感谢您的帮助! :)

您可以从插入列表中省略 MQ_Id 并让它默认。其他值需要使用 SELECT 语句提供,并且您需要占位符以便在调用 execute.

时传递参数

像这样(未测试)

my $insert = $dbh->prepare(<<__END_SQL__);
INSERT INTO mhqc (fieldnum, result, File_Id)
SELECT ?, ?, File_Id FROM records WHERE fname = ?
__END_SQL__

for my $i ( 0 .. $#fields ) {
  my $fieldnum = $fields[$i];
  my $result   = $results[$i];
  $insert->execute($fieldnum, $result, $in_file);
}