0

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

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

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

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

==>我的目标是在单个语句中使用多次插入将所有 3 个(比如说)位置插入到“位置”表中,并获得所有 3 个 last_insert_ids。

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

在这里,我将如何在数组中获取这个 last_insert_ids?

4

2 回答 2

0

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

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但它应该可以工作。

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

我希望它符合您的需求。

于 2013-12-16T13:26:40.583 回答
-2

您可以使用事务并获取 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.

来自Last Insert ID文档。

于 2013-12-16T13:23:13.670 回答