MySQL 如何重置表的主键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1809893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to reset the primary key of a table?
提问by Kaveh
In my table tbphotos
I had a 100 records. I then deleted all the records and now that I want to restart data entry I see that my primary key doesn't start from 1, but it starts from 101,
在我的表中,tbphotos
我有 100 条记录。然后我删除了所有记录,现在我想重新启动数据输入,我看到我的主键不是从 1 开始,而是从 101 开始,
Is there any way to reset the primary key?
有没有办法重置主键?
I am using MySQL administrator account.
我正在使用 MySQL 管理员帐户。
回答by Donnie
alter table foo AUTO_INCREMENT = 1
alter table foo AUTO_INCREMENT = 1
回答by Mark Byers
You can reset the auto-increment like this:
您可以像这样重置自动增量:
ALTER TABLE tablename AUTO_INCREMENT = 1
But if you are relying on the autoincrement values, your program is very fragile. If you need to assign consecutive numbers to your records for your program to work you should create a separate column for that, and not use a database auto-increment ID for this purpose.
但是如果你依赖于自动增量值,你的程序就非常脆弱。如果您需要为您的记录分配连续编号以使您的程序工作,您应该为此创建一个单独的列,而不是为此目的使用数据库自动增量 ID。
回答by Vladimir Kocjancic
If you use TRUNC instead of manually deleting records, your primary key will be reset.
如果您使用 TRUNC 而不是手动删除记录,您的主键将被重置。
回答by icynets
The code below is best if you have some data in the database already but want to reset the ID from 1 without deleting the data. Copy and run in SQL command
如果您已经在数据库中有一些数据,但想要在不删除数据的情况下将 ID 从 1 重置,则下面的代码是最好的。在 SQL 命令中复制并运行
ALTER TABLE members DROP ID;
ALTER TABLE members AUTO_INCREMENT = 1;
ALTER TABLE members ADD ID int UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;
回答by ramadhan ibrahim
This is the best script for reset auto increment:
这是重置自动增量的最佳脚本:
ALTER TABLE foo MODIFY your column increment int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
ALTER TABLE foo MODIFY your column increment int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;