How do I change the Auto Increment counter in MySQL?

喜你入骨 提交于 2019-12-03 01:08:06
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:

  1. Backup your database
  2. Drop the id column
  3. Export the data
  4. TRUNCATE or 'Empty' the table
  5. Recreate the id column as auto_increment
  6. 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:

  1. By executing a query, like others already explained:

    ALTER TABLE <table_name> AUTO_INCREMENT=<table_id>;

  2. 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. Choose Options 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.

marspzb

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!