Using LAST_INSERT_ID() within a multi row insert

后端 未结 2 432
小蘑菇
小蘑菇 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.) "

提交回复
热议问题