MySQL Eliminar todas las filas de la tabla y restablecer ID a cero


Necesito eliminar todas las filas de una tabla, pero cuando agrego una nueva fila, quiero que el ID de clave primaria, que tiene un incremento automático, comience de nuevo desde 0 respectivamente desde 1.

 158
Author: Michael Currie, 2012-09-29

4 answers

No borrar, usar truncar:

Truncate table XXX

El controlador de tabla no recuerda el último valor AUTO_INCREMENT usado, pero comienza a contar desde el principio. Esto es cierto incluso para MyISAM e InnoDB, que normalmente no reutilizan los valores de secuencia.

Source .

 270
Author: F--,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-03 07:33:43

Si no puede usar TRUNCATE (por ejemplo, debido a restricciones de clave externa) puede usar una tabla alter después de eliminar todas las filas para reiniciar el incremento automático:

ALTER TABLE mytable AUTO_INCREMENT = 1
 72
Author: a_horse_with_no_name,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-29 10:47:05

Si la tabla tiene claves foráneas, siempre utilizo el siguiente código:

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 ;

Pero la diferencia estará en el tiempo de ejecución. Mira arriba la respuesta de Sorin.

 14
Author: blacky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 08:45:08

Un hecho interesante.

Estaba seguro de que TRUNCATE siempre funcionará mejor, pero en mi caso, para una base de datos con aproximadamente 30 tablas con claves foráneas, pobladas con solo unas pocas filas, tomó aproximadamente 12 segundos TRUNCATE todas las tablas, en lugar de solo unos pocos cientos de milisegundos para DELETE las filas. Establecer el incremento automático agrega aproximadamente un segundo en total, pero aún así es mucho mejor.

Así que sugeriría probar ambos, ver cuál funciona más rápido para su caso.

 6
Author: Sorin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-31 17:51:58