How to Reset an MySQL AutoIncrement using a MAX value from another table?

前端 未结 8 666
遥遥无期
遥遥无期 2020-12-08 07:04

I know this won\'t work, tried it in various forms and failed all times. What is the simplest way to achieve the following result?

ALTER TABLE XYZ AUTO_INCRE         


        
相关标签:
8条回答
  • 2020-12-08 07:35

    Personally I'd probably use either a shell script or a little C#/C++ application or PHP/Ruby/Perl script to do this in 2 queries:

    • Grab the value you want SELECT MAX(ID) FROM ABC;
    • Alter the table using the value ALTER TABLE XYZ AUTO_INCREMENT = <insert value retrieved from first query here>

    Obviously being careful that the new auto increment won't cause any key clashes with existing data in the XYZ table.

    0 讨论(0)
  • 2020-12-08 07:36

    following the mysql docs, this worked for me in mysql 5.7:

    SET @m = (SELECT MAX(id) + 1 FROM ABC); 
    SET @s = CONCAT('ALTER TABLE XYZ AUTO_INCREMENT=', @m);
    PREPARE stmt1 FROM @s;
    EXECUTE stmt1;
    DEALLOCATE PREPARE stmt1;
    
    0 讨论(0)
提交回复
热议问题