Mysql mulitple row insert-select statement with last_insert_id()

前端 未结 2 647
无人及你
无人及你 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.

    0 讨论(0)
  • 2020-12-15 14:10

    This case may call for a cursor based solution, where you loop over the old users, and do the 2 individual inserts. This won't do bulk inserts, but it will be better then updating the rows manually.

    DELIMITER $$
    DROP PROCEDURE IF EXISTS MigrateUsers $$
    CREATE PROCEDURE MigrateUsers ()
    BEGIN
      DECLARE done INT DEFAULT 0;
      DECLARE user_id INT;
      DECLARE namefirst VARCHAR(20);
      DECLARE namelast VARCHAR(20);
      DECLARE other VARCHAR(10);
      DECLARE lid INT;
      /*Cursor looping over old users*/
      DECLARE cur CURSOR FOR
        SELECT user_id, namefirst, namelast, other
        FROM dbOLD.user;
    
      DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
    
      OPEN cur;
      START TRANSACTION; 
      read_loop: LOOP
        FETCH cur INTO user_id, namefirst, namelast, other;
        IF done THEN
          LEAVE read_loop;
        END IF;
        /*Insert entity part*/
        INSERT INTO dbNEW.entity (commonName, surname)
          VALUES (namefirst, namelast);
        SET lid = LAST_INSERT_ID();
        /*Insert user part*/
        INSERT INTO dbNEW.user (userID, entityID, other)  
        VALUES (user_id, lid, other);
    
      END LOOP;
      COMMIT;
      CLOSE cur;
    END$$
    DELIMITER ;
    

    I suggest you read the docs on Procedures and Cursors

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