How to reset AUTO_INCREMENT in MySQL?

2018-12-31 02:13发布

How can I reset the AUTO_INCREMENT of a field? I want it to start counting from 1 again.

22条回答
忆尘夕之涩
2楼-- · 2018-12-31 02:45

To update latest plus one id

 ALTER TABLE table_name AUTO_INCREMENT = 
 (SELECT (id+1) id FROM table_name order by id desc limit 1);
查看更多
墨雨无痕
3楼-- · 2018-12-31 02:46

Simply like this:

ALTER TABLE tablename AUTO_INCREMENT = value;

reference: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

查看更多
刘海飞了
4楼-- · 2018-12-31 02:47
SET  @num := 0;

UPDATE your_table SET id = @num := (@num+1);

ALTER TABLE your_table AUTO_INCREMENT =1;

I think this will do it

查看更多
裙下三千臣
5楼-- · 2018-12-31 02:48

You can reset the counter with:

ALTER TABLE tablename AUTO_INCREMENT = 1

For InnoDB you cannot set the auto_increment value lower or equal to the highest current index. (quote from ViralPatel):

Note that you cannot reset the counter to a value less than or equal to any that have already been used. For MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum plus one. For InnoDB, if the value is less than the current maximum value in the column, no error occurs and the current sequence value is not changed.

See How to Reset an MySQL AutoIncrement using a MAX value from another table? on how to dynamically get an acceptable value.

查看更多
与风俱净
6楼-- · 2018-12-31 02:48

enter image description hereThere is a very easy way with phpmyadmin under the "operations" tab, you can set, in the table options, autoincrement to the number you want.

查看更多
余生请多指教
7楼-- · 2018-12-31 02:48

Here is my solution, but I will not advise to do this if your column has constraints or is connected as foreign key to other tables as it would have bad effects or will not even work.

> First : drop the column

ALTER TABLE tbl_name DROP COLUMN column_id

> Second : recreate the column and set it as FIRST if you want it as the first column I assume.

ALTER TABLE tbl_access ADD COLUMN `access_id` int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST

This works well!

查看更多
登录 后发表回答