简体   繁体   中英

MySQL: Resetting AUTO_INCREMENT

I am trying to reset the auto increment value in one of my tables based on the number of rows currently in it. Here is the code I have so far.

SET @numrows = 0;

SELECT COUNT(*) total, @numrows := COUNT(*) + 1 numrows FROM maj_user ;
ALTER TABLE `maj_user` AUTO_INCREMENT = @numrows ;

This works great if I execute it in MySQL Workbench. However, I need to save this as an SQL file and execute it as part of a database import script. If I do this, I get this:

ERROR 1064 (42000) at line 39: You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right syntax to
use near '@numrows' at line 1

Line 39 is the ALTER TABLE statement. Any ideas?

Can you change your syntax to skip actually setting @numrows? I'm not sure what the problem is but a workaround seems to be something like:

ALTER TABLE `maj_user` AUTO_INCREMENT = (SELECT COUNT(*) + 1 from maj_user);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM