Using LAST_INSERT_ID() within a multi row insert

后端 未结 2 405
小蘑菇
小蘑菇 2021-01-25 11:39

Is it possible to use LAST_INSERT_ID() within an insert query?

INSERT INTO mytable (col1, col2) VALUES (\'val1\', null), (\'val2\', LAST_INSERT_ID())


        
相关标签:
2条回答
  • 2021-01-25 12:14

    I think that this explains it well (http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id):

    "The currently executing statement does not affect the value of LAST_INSERT_ID(). Suppose that you generate an AUTO_INCREMENT value with one statement, and then refer to LAST_INSERT_ID() in a multiple-row INSERT statement that inserts rows into a table with its own AUTO_INCREMENT column. The value of LAST_INSERT_ID() will remain stable in the second statement; its value for the second and later rows is not affected by the earlier row insertions. (However, if you mix references to LAST_INSERT_ID() and LAST_INSERT_ID(expr), the effect is undefined.) "

    0 讨论(0)
  • 2021-01-25 12:19

    From what i found it won't work as LAST_INSERT_ID doesn't have a value until the whole statement has finished.

    0 讨论(0)
提交回复
热议问题