简体   繁体   English

如何在 MySQL 中重置 AUTO_INCREMENT

[英]How to reset AUTO_INCREMENT in MySQL

How can I reset the AUTO_INCREMENT of a field?如何重置字段的AUTO_INCREMENT

I want it to start counting from 1 again.我希望它再次从1开始计数。

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.对于InnoDB ,您不能将auto_increment值设置为低于或等于当前最高索引。 (quote from ViralPatel ): (引自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.对于 MyISAM,如果该值小于或等于 AUTO_INCREMENT 列中当前的最大值,则将该值重置为当前最大值加一。 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.对于 InnoDB,如果该值小于该列中当前的最大值,则不会发生错误,并且当前序列值不会改变。

See How can I reset an MySQL AutoIncrement using a MAX value from another table?请参阅如何使用另一个表中的 MAX 值重置 MySQL AutoIncrement? on how to dynamically get an acceptable value.关于如何动态获得可接受的值。

ALTER TABLE tablename AUTO_INCREMENT = 1
SET  @num := 0;

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

ALTER TABLE your_table AUTO_INCREMENT =1;

Simply like this:就像这样:

ALTER TABLE tablename AUTO_INCREMENT = value;

Reference: 13.1.9 ALTER TABLE Statement参考: 13.1.9 ALTER TABLE 语句

在此处输入图像描述

There is a very easy way with phpMyAdmin under the "operations" tab.在“操作”选项卡下使用phpMyAdmin有一个非常简单的方法。 In the table options you can set autoincrement to the number you want.在表格选项中,您可以将自动增量设置为您想要的数字。

The best solution that worked for me:对我有用的最佳解决方案:

ALTER TABLE my_table MODIFY COLUMN ID INT(10) UNSIGNED;
COMMIT;
ALTER TABLE my_table MODIFY COLUMN ID INT(10) UNSIGNED AUTO_INCREMENT;
COMMIT;

It's fast, works with InnoDB, and I don't need to know the current maximum value!它很快,与 InnoDB 一起工作,我不需要知道当前的最大值!

This way.这边走。 the auto increment counter will reset and it will start automatically from the maximum value exists.自动递增计数器将重置并从存在的最大值自动开始。

The highest rated answers to this question all recommend "ALTER yourtable AUTO_INCREMENT= value".这个问题的评分最高的答案都推荐“ALTER yourtable AUTO_INCREMENT= value”。 However, this only works when value in the alter is greater than the current max value of the autoincrement column.但是,这仅在更改中的value大于自动增量列的当前最大值时才有效。 According to the MySQL 8 documentation :根据 MySQL 8 文档

You cannot reset the counter to a value less than or equal to the value that is currently in use.您不能将计数器重置为小于或等于当前使用的值。 For both InnoDB and 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 AUTO_INCREMENT column value plus one.对于 InnoDB 和 MyISAM,如果该值小于或等于 AUTO_INCREMENT 列中当前的最大值,则将该值重置为当前最大 AUTO_INCREMENT 列值加一。

In essence, you can only alter AUTO_INCREMENT to increase the value of the autoincrement column, not reset it to 1, as the OP asks in the second part of the question.本质上,您只能更改 AUTO_INCREMENT 以增加自动增量列的值,而不是将其重置为 1,正如 OP 在问题的第二部分中所问的那样。 For options that actually allow you set the AUTO_INCREMENT downward from its current max, take a look at Reorder / reset auto increment primary key .对于实际上允许您从当前最大值向下设置 AUTO_INCREMENT 的选项,请查看Reorder / reset auto increment primary key

As of MySQL 5.6 you can use the simple ALTER TABLE with InnoDB:从 MySQL 5.6 开始,您可以将简单的 ALTER TABLE 与 InnoDB 一起使用:

ALTER TABLE tablename AUTO_INCREMENT = 1;

The documentation are updated to reflect this:文档已更新以反映这一点:

13.1.7 ALTER TABLE Statement 13.1.7 ALTER TABLE 语句

My testing also shows that the table is not copied.我的测试还表明该表没有被复制。 The value is simply changed.值只是简单地改变了。

There are good options given in How To Reset MySQL Autoincrement Column How To Reset MySQL Autoincrement Column 中给出了很好的选择

Note that ALTER TABLE tablename AUTO_INCREMENT = value;注意ALTER TABLE tablename AUTO_INCREMENT = value; does not work for InnoDB不适用于InnoDB的工作

You can also use the syntax TRUNCATE table like this:您还可以像这样使用语法TRUNCATE表:

TRUNCATE TABLE table_name

Beware!谨防! TRUNCATE TABLE your_table will delete everything in your your_table . TRUNCATE TABLE your_table删除your_table中的所有内容。

ALTER TABLE news_feed DROP id

ALTER TABLE news_feed ADD  id BIGINT( 200 ) NOT NULL AUTO_INCREMENT FIRST ,ADD PRIMARY KEY (id)

I used this in some of my scripts.我在我的一些脚本中使用了它。 The id field is dropped and then added back with previous settings. id 字段被删除,然后使用以前的设置添加回来。 All the existent fields within the database table are filled in with the new auto increment values.数据库表中的所有现有字段都使用新的自动增量值填充。 This should also work with InnoDB .这也应该适用于InnoDB

Note that all the fields within the table will be recounted and will have other ids!!!.请注意,表中的所有字段都将被重新计算,并且将具有其他 ID!!!。

It is for an empty table:这是一个空表:

ALTER TABLE `table_name` AUTO_INCREMENT = 1;

If you have data, but you want to tidy up it, I recommend to use this:如果你有数据,但你想整理一下,我建议使用这个:

ALTER TABLE `table_name` DROP `auto_colmn`;
ALTER TABLE `table_name` ADD  `auto_colmn` INT( {many you want} ) NOT NULL AUTO_INCREMENT FIRST ,ADD PRIMARY KEY (`auto_colmn`);

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.第二:重新创建列并将其设置为 FIRST,如果您希望它作为我假设的第一列。

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

从 MySQL 5.6 开始,由于在线 DDL (注意algorithm=inplace ),以下方法运行得更快:

alter table tablename auto_increment=1, algorithm=inplace;

SET @num := 0;
UPDATE your_table SET id = @num := (@num+1);
ALTER TABLE your_table AUTO_INCREMENT =1;

To update to the latest plus one id:要更新到最新的加一个 id:

 ALTER TABLE table_name AUTO_INCREMENT = 
 (SELECT (id+1) id FROM table_name order by id desc limit 1);

Edit:编辑:

SET @latestId = SELECT MAX(id) FROM table_name;
SET @nextId = @latestId + 1;
ALTER TABLE table_name AUTO_INCREMENT = @nextId;

Not tested please test before you run*未测试,请在运行前测试*

Try to run this query:尝试运行此查询:

 ALTER TABLE tablename AUTO_INCREMENT = value;

Or try this query for the reset auto increment或者试试这个查询重置自动增量

 ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL;

And set auto increment and then run this query:并设置自动增量,然后运行此查询:

  ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;

The auto-increment counter for a table can be (re)set in two ways:可以通过两种方式(重新)设置表的自动增量计数器:

  1. By executing a query, like others already explained:通过执行查询,就像其他人已经解释的那样:

    ALTER TABLE <table_name> AUTO_INCREMENT=<table_id>;

  2. Using Workbench or another visual database design tool.使用Workbench或其他可视化数据库设计工具。 I am going to show in Workbench how it is done - but it shouldn't be much different in other tools as well.我将在 Workbench 中展示它是如何完成的——但在其他工具中也不应该有太大的不同。 By right clicking over the desired table and choosing Alter table from the context menu.通过右键单击所需的表并从上下文菜单中选择Alter table On the bottom you can see all the available options for altering a table.在底部,您可以看到更改表格的所有可用选项。 Choose Options and you will get this form:选择Options ,您将获得此表格:

    在此处输入图像描述

Then just set the desired value in the field Auto increment as shown in the image.然后只需在字段Auto increment中设置所需的值,如图所示。 This will basically execute the query shown in the first option.这将基本上执行第一个选项中显示的查询。

如果您使用PHPStorm's database tool ,您必须在database console中输入:

ALTER TABLE <table_name> AUTO_INCREMENT = 0;

I tried to alter the table and set auto_increment to 1 but it did not work.我试图更改表并将 auto_increment 设置为 1,但它不起作用。 I resolved to delete the column name I was incrementing, then create a new column with your preferred name and set that new column to increment from the onset.我决定删除我正在递增的列名,然后使用您的首选名称创建一个新列,并将该新列设置为从一开始就递增。

您可以简单地截断表格以重置序列:

TRUNCATE TABLE TABLE_NAME

I googled and found this question, but the answer I am really looking for fulfils two criteria:我用谷歌搜索并找到了这个问题,但我真正想要的答案满足两个标准:

  1. using purely MySQL queries使用纯 MySQL 查询
  2. reset an existing table auto-increment to max(id) + 1将现有表自动增量重置为 max(id) + 1

Since I couldn't find exactly what I want here, I have cobbled the answer from various answers and sharing it here.因为我在这里找不到我想要的东西,所以我从各种答案中拼凑出答案并在这里分享。

Few things to note:有几点需要注意:

  1. the table in question is InnoDB有问题的表是 InnoDB
  2. the table uses the field id with type as int as primary key该表使用类型为int的字段id作为主键
  3. the only way to do this purely in MySQL is to use stored procedure纯粹在 MySQL 中执行此操作的唯一方法是使用存储过程
  4. my images below are using SequelPro as the GUI.我下面的图片使用 SequelPro 作为 GUI。 You should be able to adapt it based on your preferred MySQL editor您应该能够根据您喜欢的 MySQL 编辑器对其进行调整
  5. I have tested this on MySQL Ver 14.14 Distrib 5.5.61, for debian-linux-gnu我已经在 MySQL Ver 14.14 Distrib 5.5.61 上测试了这个,用于 debian-linux-gnu

Step 1: Create Stored Procedure第 1 步:创建存储过程

create a stored procedure like this:创建一个这样的存储过程:

DELIMITER //
CREATE PROCEDURE reset_autoincrement(IN tablename varchar(200))
BEGIN

      SET @get_next_inc = CONCAT('SELECT @next_inc := max(id) + 1 FROM ',tablename,';');
      PREPARE stmt FROM @get_next_inc;
      EXECUTE stmt;
      SELECT @next_inc AS result;
      DEALLOCATE PREPARE stmt;

      set @alter_statement = concat('ALTER TABLE ', tablename, ' AUTO_INCREMENT = ', @next_inc, ';');
      PREPARE stmt FROM @alter_statement;
      EXECUTE stmt;
      DEALLOCATE PREPARE stmt;
END //
DELIMITER ;

Then run it.然后运行它。

Before run, it looks like this when you look under Stored Procedures in your database.在运行之前,当您查看数据库中的存储过程时,它看起来像这样。

在此处输入图像描述

When I run, I simply select the stored procedure and press Run Selection当我运行时,我只需选择存储过程并按运行选择

在此处输入图像描述

Note: the delimiters part are crucial.注意:分隔符部分至关重要。 Hence if you copy and paste from the top selected answers in this question, they tend not to work for this reason.因此,如果您复制并粘贴此问题中最热门的答案,它们往往因此不起作用。

After I run, I should see the stored procedure运行后,我应该看到存储过程

在此处输入图像描述

If you need to change the stored procedure, you need to delete the stored procedure, then select to run again.如果需要更改存储过程,则需要删除存储过程,然后选择再次运行。

Step 2: Call the stored procedure第二步:调用存储过程

This time you can simply use normal MySQL queries.这次你可以简单地使用普通的 MySQL 查询。

call reset_autoincrement('products');

Originally from my own SQL queries notes in https://simkimsia.com/reset-mysql-autoincrement-to-max-id-plus-1/ and adapted for Stack Overflow.最初来自我自己在https://simkimsia.com/reset-mysql-autoincrement-to-max-id-plus-1/中的 SQL 查询注释,并适用于 Stack Overflow。

ALTER TABLE `table_name`   DROP `id`;

ALTER TABLE `table_name` ADD `id` INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`id`) ;

Shortly,First we deleted id column then added it with primary key id again...很快,首先我们删除了 id 列,然后再次添加了主键 id ......

ALTER TABLE tablename AUTO_INCREMENT = 1

The best way is remove the field with AI and add it again with AI.最好的方法是使用 AI 删除字段并使用 AI 再次添加。 It works for all tables.它适用于所有表。

You need to follow the advice from Miles M's comment and here is some PHP code that fixes the range in MySQL.您需要遵循 Miles M 评论中的建议,这里有一些PHP代码可以修复 MySQL 中的范围。 Also you need to open up the my.ini file (MySQL) and change max_execution_time=60 to max_execution_time=6000;您还需要打开my.ini文件(MySQL)并将 max_execution_time=60 更改为 max_execution_time=6000; for large databases.对于大型数据库。

Don't use "ALTER TABLE tablename AUTO_INCREMENT = 1".不要使用“ALTER TABLE 表名 AUTO_INCREMENT = 1”。 It will delete everything in your database.它将删除数据库中的所有内容。

$con = mysqli_connect($dbhost, $dbuser, $dbpass, $database);
$res = mysqli_query($con, "select * FROM data WHERE id LIKE id ORDER BY id ASC");

$count = 0;
while ($row = mysqli_fetch_array($res)){
    $count++;

    mysqli_query($con, "UPDATE data SET id='".$count."' WHERE id='".$row['id']."'");
}
echo 'Done reseting id';
mysqli_close($con);

I suggest you to go to Query Browser and do the following:我建议您转到查询浏览器并执行以下操作:

  1. Go to schemata and find the table you want to alter.转到 schemata 并找到要更改的表。

  2. Right click and select copy create statement.右键单击并选择复制创建语句。

  3. Open a result tab and paste the create statement their.打开一个结果选项卡并粘贴其创建语句。

  4. Go to the last line of the create statement and look for the Auto_Increment=N, (Where N is a current number for auto_increment field.)转到 create 语句的最后一行并查找 Auto_Increment=N,(其中 N 是 auto_increment 字段的当前编号。)

  5. Replace N with 1.将 N 替换为 1。

  6. Press Ctrl + Enter .Ctrl + Enter

Auto_increment should reset to one once you enter a new row in the table.在表中输入新行后, Auto_increment应重置为 1。

I don't know what will happen if you try to add a row where an auto_increment field value already exist.我不知道如果您尝试添加已经存在auto_increment 字段值的行会发生什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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