同时或同时将 lastInsertId 从一个表插入到另一个表的可能方法 [英] Possible way to insert lastInsertId from one table to another at the same time or simultaneously

查看:50
本文介绍了同时或同时将 lastInsertId 从一个表插入到另一个表的可能方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景是我有两个表,我们可以称之为 table_a 和 table_b.一个有 4 列,另一个有 3 列,这是它们的样子

The scenario is I have two table, we can call it table_a and table_b. one have 4 column, and the other one has 3, here is what they look like

table_a                        table_b
+------+------+-----+----+       +-----+-----+-----+
| a_id | name | age |sex |       |b_id |a_id |type |
+------+------+-----+----+       +-----+-----+-----+

我有一个查询同时向两个表插入数据

I have a query that insert a data to the two table at the same time

$query = "INSERT INTO table_a SET name=:name, age=:age, sex=:sex; INSERT INTO table_b SET   type=:type";
$stmt = $this->conn->prepare($query);
$this->name = $this->name;
$this->name = $this->age;
$this->name = $this->sex;
$this->name = $this->type;
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':age', $this->age);
$stmt->bindParam(':sex', $this->sex);
$stmt->bindParam(':type', $this->type);
if($stmt->execute()){
   return $this->conn->lastInsertId();
 }else{ 
   return -1;}

table_a 上的 a_id 是类似于 table_b 中的 b_id 的自动增量,姓名、年龄、性别、类型都是用户使用

a_id on table_a is autoincrement similar to b_id in table_b, name, age, sex, type were all inserted by user using

$_POST

现在,我的问题是,有没有办法可以自动将 table_a 中的 a_id 值放入 table_b 中的 a_id?lastInsertId 工作正常,但我不确定如何将它放在另一张桌子上.我也在考虑另一个解决方案,那就是使用这个

Now, my inquiry, is there a way I can automatically put a_id value from table_a to a_id in table_b? The lastInsertId is working properly, though Im not sure how I can put it on the other table. I am also thinking about another solution, and that is assigning a value to a_id using this

a_id=:LAST_INSERT_ID() 

但我不知道该怎么做,或者是否可能.

But I am not sure how to do that or if it is possible.

推荐答案

试试这个:

INSERT INTO table_a SET name=:name, age=:age, sex=:sex; INSERT INTO table_b SET a_id=LAST_INSERT_ID(), type=:type;

这篇关于同时或同时将 lastInsertId 从一个表插入到另一个表的可能方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆