Reserving mySQL auto-incremented IDs?

前端 未结 3 1952
既然无缘
既然无缘 2021-02-15 14:15

We want to obtain an auto-increment ID from mySQL without actually storing it until the other non-mysql related processes are successfully completed, so that the entry is not st

3条回答
  •  梦谈多话
    2021-02-15 15:08

    The only way to generate an auto-increment value is to attempt the insert. But you can roll back that transaction, and still read the id generated. In MySQL 5.1 and later, the default behavior is that auto-increment values aren't "returned" to the stack when you roll back.

    START TRANSACTION;
    INSERT INTO mytable () VALUES ();
    ROLLBACK;
    SELECT LAST_INSERT_ID() INTO @my_ai_value;
    

    Now you can be sure that no other transaction will try to use that value, so you can use it in your external processes, and then finally insert a value manually that uses that id value (when you insert a specific id value, MySQL does not generate a new value).

提交回复
热议问题