简体   繁体   English

MySQL 删除表中的所有行并将 ID 重置为零

[英]MySQL Delete all rows from table and reset ID to zero

我需要从表中删除所有行,但是当我添加新行时,我希望主键 ID 具有自动增量,分别从 0 开始,分别从 1 开始。

Do not delete, use truncate:不要删除,使用truncate:

Truncate table XXX

The table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning.表处理程序不记得上次使用的 AUTO_INCREMENT 值,而是从头开始计数。 This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.即使对于通常不重用序列值的 MyISAM 和 InnoDB 也是如此。

Source . 来源

如果您不能使用TRUNCATE (例如由于外键约束),您可以在删除所有行后使用更改表来重新启动 auto_increment:

ALTER TABLE mytable AUTO_INCREMENT = 1

If table has foreign keys then I always use following code:如果表有外键,那么我总是使用以下代码:

SET FOREIGN_KEY_CHECKS = 0; -- disable a foreign keys check
SET AUTOCOMMIT = 0; -- disable autocommit
START TRANSACTION; -- begin transaction

/*
DELETE FROM table_name;
ALTER TABLE table_name AUTO_INCREMENT = 1;
-- or
TRUNCATE table_name;
-- or
DROP TABLE table_name;
CREATE TABLE table_name ( ... );
*/

SET FOREIGN_KEY_CHECKS = 1; -- enable a foreign keys check
COMMIT;  -- make a commit
SET AUTOCOMMIT = 1 ;

But difference will be in execution time.但不同之处在于执行时间。 Look at above Sorin's answer.看看上面索林的回答。

An interesting fact.一个有趣的事实。

I was sure TRUNCATE will always perform better, but in my case, for a database with approximately 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows.我确信TRUNCATE总是会表现得更好,但在我的情况下,对于一个有大约 30 个带有外键的表的数据库,只填充了几行, TRUNCATE所有表需要大约 12 秒,而不是只有几百毫秒DELETE行。 Setting the auto increment adds about a second in total, but it's still a lot better.设置自动增量总共增加了大约一秒钟,但它仍然好得多。

So I would suggest try both, see which works faster for your case.所以我建议两者都尝试,看看哪个更适合你的情况。

if you want to use truncate use this:如果你想使用truncate使用这个:

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

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

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