SQL >> Base de Datos >  >> RDS >> Mysql

MySQL: SHOW TABLE STATUS devuelve un AUTO_INCREMENT desactualizado

Esto no es un bug, es una característica. Las estadísticas de tabla se almacenan en caché, así que el valor de Auto_increment que informa SHOW TABLE STATUS puede ir por detrás de la realidad. Para desactivar la caché y leer siempre valores frescos, fija la duración de la caché a cero:

SET PERSIST information_schema_stats_expiry = 0

En MySQL 8.x el valor por defecto es 86400 (24 horas), y por eso el número parece congelado.

Ver el valor obsoleto en acción

SET PERSIST information_schema_stats_expiry = 86400 -- 86400 is the default value of mysql 8.x if you have never changed this you don't need to set this show variables like 'information_schema_stats_expiry'; +---------------------------------+-------+ | Variable_name | Value | +---------------------------------+-------+ | information_schema_stats_expiry | 86400 | +---------------------------------+-------+ create schema mytest; create table `test` ( `id` int(5) not null auto_increment, `name` varchar(256), PRIMARY KEY(`id`) ); insert into test values(null,'name1') insert into test values(null,'name2') insert into test values(null,'name3') show table status where name like 'test';

En este punto Auto_increment indica 4, correctamente. Inserta otra fila y vuelve a consultar:

insert into test values(null,'name3'); show table status where name like 'test'; -- The Auto_increment is still 4 (it was cached). drop schema mytest

Después de desactivar la caché

SET PERSIST information_schema_stats_expiry = 0

Ejecutando la misma prueba ahora, el contador avanza como se espera:

show variables like 'information_schema_stats_expiry'; +---------------------------------+-------+ | Variable_name | Value | +---------------------------------+-------+ | information_schema_stats_expiry | 0 | +---------------------------------+-------+ create schema mytest; create table `test` ( `id` int(5) not null auto_increment, `name` varchar(256), PRIMARY KEY(`id`) ); insert into test values(null,'name1'); insert into test values(null,'name2'); insert into test values(null,'name3'); show table status where name like 'test'; -- Auto_increment is 4, but the result is not cached! insert into test values(null,'name3'); show table status where name like 'test'; -- The Auto_increment field is now 5 (a correct, not cached value) drop schema mytest;

Fija la expiración a 0 y el Auto_increment informado será exacto después de cada inserción.