如何在运行单个语句多次插入查询后获取所有last_insert_id


How to get all last_insert_ids after running a single statement multiple insert query?

我有一个'location'表和'location_detail'[用于插入不同的语言数据]表。'location_detail’包含位置表的FK

我需要一次输入多个位置。所以我正在做的是:

在其中运行一个"for"循环,首先我将数据输入到"location"表中,获取loc_id,然后插入到location_detail表中[如果存在多种语言,请在"location_detail"表中显示,我想再次运行查询多次]。

因此,如果我想添加3个位置->外部"for"循环将运行3次查询exec的总数。是6[如果存在一种以上的语言,则会有多种]

===>我的目标是在一条语句中使用多个insert将所有3个位置插入到"location"表中,并获得所有3个last_insert_id。

===>接下来,我可以运行单语句多插入查询,以添加到"location_details"表中

在这里,如何在数组中获取此last_insert_ids?

我将在同一事务/连接中执行此操作:

INSERT INTO location (col1, col2) VALUES (val1a, val2a); 
SET @string_ids = LAST_INSERT_ID();
INSERT INTO location (col1, col2) VALUES (val1b, val2b); 
SET @string_ids = CONCAT(@string_ids , ",", LAST_INSERT_ID());
INSERT INTO location (col1, col2) VALUES (val1c, val2c); 
SET @string_ids = CONCAT(@string_ids , ",", LAST_INSERT_ID());
SELECT @string_ids ;

然后在php中,我会分解这个变量:

$array_ids = explode (",", $string_ids ).

然后使用php:构建您的请求

INSERT INTO location_detail(id, fk_id) VALUES 
//foreach loop
     (val_id1b, $array_ids[$i] )
     (val_id2b, $array_ids[$i] )
     (val_id3b, $array_ids[$i] )

我还没有试过@array_ids,但它应该能用。

如果您需要,请查看此链接以获得更多帮助。

我希望它能满足你的需要。

您可以使用transaction并获取last_insert_id,并计算与AUTO_INCREMENT设置相关的先前id。

Important
If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for the first inserted row only. The reason for this is to make it possible to reproduce easily the same INSERT statement against some other server.

来自上次插入ID文档。