Mysql mulitple row insert-select statement with last_insert_id()

前端 未结 2 661
无人及你
无人及你 2020-12-15 13:49

Ok. So the short of it is, I was trying to do an INSERT SELECT such as:

START TRANSACTION;  
INSERT INTO dbNEW.entity (commonName, surname)  
SELECT namefirs         


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 13:54

    For the last query, use this

    INSERT INTO dbNEW.`user` (userID, entityID, other)  
    SELECT user_id, entityID, other
    FROM
    (
        SELECT user_id, @key + @rn entityID, other, @rn := @rn + 1
        FROM (select @rn:=0) x, dbOLD.`user`
        order by user_id
    ) y;
    

    The LAST_INSERT_ID() in MySQL is the FIRST id created in a batch, unlike SCOPE_IDENTITY() in SQL Server which is the LAST id. Since it is the first, we increment each row using the variable @rn, starting at addition=0 for the first row.

提交回复
热议问题