php - 如何为主表和辅助表编写 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_ID
tblParent 的多插入又在 tblChild 中为每个 tblParent 插入多个插入,将如何表现
解决方案
<?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
?>
您可以像这样使用多个插入。
推荐阅读
- r - 几何内部的条件(ggplot)
- javascript - 从 txt 文件重新加载更新文本
- html - 如何阻止谷歌博客 HTML 编辑器将单引号转换为 '
- c++ - 内置函数以查看 CPP 中的成员变量
- python - Python,Pandas Dataframe - 如何添加 API 生成的最大列数?
- python - 根据起始索引和相应长度列表删除矩阵列的最有效方法
- javascript - 需要 JavaScript(所有页面的背景和声音更改)帮助
- python - Pandas 包含 json 文件的密钥
- c++ - 是否可以初始化不可复制类型的成员变量(或基类)?
- ignite - 无法使用 DataStorageConfiguration 在锁或事务中启动/停止缓存