首页 > 解决方案 > 如何为主表和辅助表编写 SQL 多插入查询

问题描述

我有两个表,我想编写一个多插入查询,这样,第一个表中的 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 中的每条记录在 tblParent 中执行一次插入,并在 tblChild 中执行多次插入

编辑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) 的引用,则效果未定义。)

所以我的下一个问题是,如果LAST_INSERT_IDtblParent 的多插入又在 tblChild 中为每个 tblParent 插入多个插入,将如何表现

标签: phpmysqlforeign-keys

解决方案


<?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            
    ?>

您可以像这样使用多个插入。


推荐阅读