I have an ID field that is my primary key and is just an int field.
I have less than 300 rows but now every time someone signs up that ID auto inc is inputted really high like 11800089, 11800090, etc.... Is there a way to get that to come back down so it can follow the order (310,311,312).
Thanks!
ALTER TABLE tbl AUTO_INCREMENT=310;
Beware though, you don't want to repeat an ID. If the numbers are that high, they got that way somehow. Be very sure you don't have associated data with the lower ID numbers.
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
There may be a quicker way, but this is how I would do it to be sure I am recreating the IDs;
If you are using MySQL or some other SQL server, you will need to:
- Backup your database
- Drop the id column
- Export the data
TRUNCATE
or 'Empty' the table- Recreate the
id
column asauto_increment
- Reimport the data
This will destroy the IDs of the existing rows, so if these are important, it is not a viable option.
Guessing that you are using mysql because you are using PHP. You can reset the auto_increment with a statement like
alter table mytable autoincrement=301;
Be careful though - because things will break when the auto inc value overlaps
The auto increment counter for a table can be (re)set two ways:
By executing a query, like others already explained:
ALTER TABLE <table_name> AUTO_INCREMENT=<table_id>;
Using Workbench or other visual database design tool. I am gonna show in Workbench how it is done - but it shouldn't be much different in other tool as well. By right click over the desired table and choosing
Alter table
from the context menu. On the bottom you can see all the available options for altering a table. ChooseOptions
and you will get this form:Then just set the desired value in the field
Auto increment
as shown in the image. This will basically execute the query shown in the first option.
I believe that mysql does a select max on the id and puts the next. Try updating the ids of your table to the desired sequence. The problem you will have is if they're linked you should put a Cascade on the update on the fk. A query that comes to my mind is:
UPDATE Table SET id=(SELECT max(id)+1 FROM TAble WHERE id<700)
700 something less than the 11800090 you have and near to the 300 WHERE id>0;
I believe that mysql complaints if you don't put a where
I was playing around on a similar problem and found this solution:
SET @newID=0;
UPDATE `test` SET ID=(@newID:=@newID+1) ORDER BY ID;
SET @c = (SELECT COUNT(ID) FROM `test`);
SET @s = CONCAT("ALTER TABLE `test` AUTO_INCREMENT = ",@c);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I hope that helps someone in a similar situation!
来源:https://stackoverflow.com/questions/8161788/how-do-i-change-the-auto-increment-counter-in-mysql