change auto_increment within same table using subquery mysql

后端 未结 4 1165
青春惊慌失措
青春惊慌失措 2021-01-14 15:56

I am using mysql. I have a database table with auto_increment counter set. Now because of a requirement I need to leave starting 100 ids free and move all existing records s

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 16:21

    You said in your question

    Main constraint here with me is that I need to do it in single sql statement. I can not save the value using @counter and use it later.

    Actually you can try using dynamic SQL and see if it works as follows:

    SELECT (MAX(id) + 1) INTO @counter FROM role;
    SET @sql = CONCAT('ALTER TABLE role AUTO_INCREMENT=',@counter);
    PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
    

    This may or may not work. Even if it does work for you, Bill Karwin's answer shows that it would not be necessary because of how MySQL already handles auto increment values. No need to manually do what MySQL already does.

    Also note the first line in Bill's post

    The parser does not support a subquery in the place you are trying to use it.

    I wrote a crazy post explaining why in the DBA StackExchange.

    Therefore, you should accept Bill's answer because the best thing to do is nothing at all.

提交回复
热议问题