简体   繁体   English

多行插入和返回ID

[英]Multi line insert and return ids

Disclaimer: I'm working with old code that uses mysql functions instead of mysqli functions. 免责声明:我正在使用使用mysql函数而不是mysqli函数的旧代码。 I am not in a position to retrofit the code with the updated functionality and have to work within the old, depredated functions. 我无法使用更新的功能来对代码进行改造,而必须使用旧的,过时的功能。 I am aware this is not best practice. 我知道这不是最佳做法。

We are trying to use a multiline INSERT but then need to pull out the mysql_insert_id() for each inserted row. 我们正在尝试使用多行INSERT但随后需要为每个插入的行提取mysql_insert_id() Is this possible? 这可能吗?

Example: 例:

INSERT INTO banner (date, count) VALUES ('2013-06-06', 1), ('2013-06-07', 1), ('2013-06-08', 2);

How can I then grab the insert_id for each line? 然后,如何获取每行的insert_id?

I would use a transaction and loop through your data: 我将使用事务并遍历您的数据:

--- DB SET AUTOCOMMIT TO FALSE ---

--- DB START TRANSACTION ---

--- LOOP BEGIN ---

    --- INSERT ONE ROW ---

    --- YOU CAN FETCH LAST_INSERT_ID HERE AND USE/STORE IT ---

--- LOOP END ---

--- DB END TRANSACTION (COMMIT) ---

--- DB SET AUTOCOMMIT BACK TO TRUE ---

(pseudocode) (伪代码)

Perhaps you could take a different approach to this problem. 也许您可以对这个问题采取不同的方法。

Since you'll only get the ID of the last inserted row, you can easily get all the IDs based on the number of rows that are inserted (provided that you use AUTO_INCREMENT, which seems so from your code, and that you know how many rows are inserted each time). 由于您只会获得最后插入的行的ID,因此您可以根据插入的行数轻松获得所有ID(前提是您使用的是AUTO_INCREMENT,这在您的代码中是如此,而且您知道有多少行每次插入行)。 You can easily subtrack the number of added items from the last ID and you'll get the range of IDs you need. 您可以轻松地从上一个ID跟踪添加项目的数量,并获得所需ID的范围。

The range would be from Last ID - rows added + 1 to Last ID . 范围是从Last ID - rows added + 1Last ID

So for example, if you insert 5 rows and you get the ID of 42, the list of IDs would be: 38, 39, 40, 41, 42. 因此,例如,如果您插入5行并获得ID为42,则ID列表将为:38、39、40、41、42。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM