我有两个表,我想编写一个多插入查询,这样,第一个表中的PK会自动插入另一个表中的fk。
让我们假设以下表格模式:
tblParent
ParentID (Primary Key Auto increment)
ParentValue
tblChild
ChildID (Primary Key Auto increment)
FkParentID (Foreign Key)
ChildValue
现在我想编写一个如下所示的多插入查询
INSERT INTO tblParent, tblChild (ParentValue, FkParentID, ChildValue) VALUES ('Parent 1', <ParentID of 'Parent 1'>, 'Child 1'), ('Parent 2', <ParentID of 'Parent 2'>, 'Child 2'), ('Parent 3', <ParentID of 'Parent 3'>, 'Child 3')
但我不知道该怎么做。我有数百万条记录要插入这些表中。我不想在第一个表中插入记录,然后获取父ID并在第二个表中插入记录。
编辑1:我的数据库是Mysql InnoDb
编辑2:有问题的表格具有一对多的关系。所以这意味着我想在tblParent中执行一次插入,并在tblChild中为tblPild中的每个记录执行多次插入
编辑3:
我正在查看MySql文档并遇到以下描述:
https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id
当前正在执行的语句不会影响LAST_INSERT_ID()的值。假设您使用一个语句生成AUTO_INCREMENT值,然后在多行INSERT语句中引用LAST_INSERT_ID(),该语句将行插入到具有自己的AUTO_INCREMENT列的表中。 LAST_INSERT_ID()的值将在第二个语句中保持稳定;它的第二行和后一行的值不受先前行插入的影响。 (但是,如果混合对LAST_INSERT_ID()和LAST_INSERT_ID(expr)的引用,则效果未定义。)
所以我的下一个问题是,如果tblParent的多次插入,LAST_INSERT_ID
将如何表现,而tblParent又为每个tblParent在tblChild中有多个插入
<?php
//your codes
$inset_tblParent= "INSERT INTO tblParent (ParentValue, FkParentID, ChildValue)VALUES('Parent 1', <ParentID of 'Parent 1'>, 'Child 1')";
$inset_tblChild= "INSERT INTO tblChild (ParentValue, FkParentID, ChildValue)VALUES('Parent 2', <ParentID of 'Parent 2'>, 'Child 2')";
//your doces
?>
你可以像这样使用多个插件。
您可以按以下方式在两个表中插入数据: -
$result = INSERT INTO tblParent (ParentValue) VALUE('ABC');
if($result == true){
$query = SELECT * tblParent ORDER BY ParentID DESC LIMIT 1;
$row = $query->fetch_assoc();
$ParentID = $row['ParentID'];
INSERT INTO tblChild (FkParentID,ChildValue) VALUE('$ParentID','XYZ');
}
无论如何,现在我所做的是使用multi_query来插入值。
我在一个while循环中做了一些跟踪:
$autoIncForParent = <Max ID from tblParent>;
while(<condition to evaluate>) {
if (!empty($multiQuery)) {
$multiQuery .= ";";
}
$multiQuery .= "INSERT INTO tblParent (ParentID , ParentValue) VALUES ($autoIncForParent, 'Parent 1');";
$multiQuery .= "INSERT INTO tblChild (FkParentID , ChildValue) VALUES ($autoIncForParent, 'Child 1');";
$autoIncForParent++;
}
$mysqli->multi_query($multiQuery);
我很确定必须有另一种解决这个问题的好方法。
我已经处理了内存问题,竞争条件以及实际代码中没有的内容。此片段仅用于详细说明。绝不是这个片段是完美的,我不建议将其用于制作。
编辑1:添加缺少的分号。如果有人提到这个