MySQL "Показать статус таблицы", автоинкремент неверен - PullRequest
0 голосов
/ 08 октября 2018

Я создаю новую таблицу в Mysql, добавляю несколько строк, но поле Auto_increment отображаемых таблиц по-прежнему возвращает NULL.

В руководстве по mysql сказано: это поле должно возвращать: «Следующее значение Auto_increment»

https://dev.mysql.com/doc/refman/8.0/en/show-table-status.html

Что я делаю не так?

Как правильно найти следующее значение auto_increment?


Шаги для воспроизведения:

create table `test` (
  `id` int(5) not null auto_increment,
  `name` varchar(256),
  PRIMARY KEY(`id`)
);

Затем я запускаю:

show table status where name like 'test';

Результат:

Name,   Engine,   Version, ...,  Auto_increment, ... 
'test', 'InnoDB', '10',    ...,  NULL, ...

Затем я запускаю:

insert into test values(null,'name1');
insert into test values(null,'name2');
insert into test values(null,'name3');

Редактировать: - другой синтаксис вставки-

insert into test (name) values('name4');
insert into test (name) values('name5');
insert into test (name) values('name6');

Получить состояние таблицы

show table status where name like 'test';

Результат

Name,   Engine,   Version, ...,  Auto_increment, ... 
'test', 'InnoDB', '10',    ...,  NULL, ...

Данные в таблице

select * from test;

Результат:

1   name1
2   name2
3   name3

Для вашей информации:

SHOW VARIABLES LIKE "%version%";

Результат:

'innodb_version', '8.0.12'
'protocol_version', '10'
'slave_type_conversions', ''
'tls_version', 'TLSv1,TLSv1.1,TLSv1.2'
'version', '8.0.12'
'version_comment', 'MySQL Community Server - GPL'
'version_compile_machine', 'x86_64'
'version_compile_os', 'Win64'
'version_compile_zlib', '1.2.11'

Редактировать: автокоммит:

SHOW VARIABLES LIKE "autocommit";

Результат:

'autocommit', 'ON'

Редактировать:

Через некоторое время он автоматически начинает работать.Нет четкой причины, как заставить его работать.

1 Ответ

0 голосов
/ 10 октября 2018

Это особенность .. не ошибка.

Статистика таблицы кэшируется.Чтобы отключить кэш и всегда иметь последнюю версию, необходимо изменить переменную сервера, которая указывает продолжительность очистки кеша, на 0:

SET PERSIST information_schema_stats_expiry = 0

Значение этого свойства по умолчанию изменилось на 86400 (24 часа) в Mysql 8.x

Пример:

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';
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation          | Checksum | Create_options | Comment |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| test | InnoDB |      10 | Dynamic    |    3 |           5461 |       16384 |               0 |            0 |         0 |              4 | 2018-10-09 15:32:15 | 2018-10-09 15:32:16 | NULL       | utf8mb4_0900_ai_ci |     NULL |                |         |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
-- The Auto_increment field is correctly set to 4.. but is now cached.

insert into test values(null,'name3');

show table status where name like 'test';
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation          | Checksum | Create_options | Comment |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| test | InnoDB |      10 | Dynamic    |    3 |           5461 |       16384 |               0 |            0 |         0 |              4 | 2018-10-09 15:32:15 | 2018-10-09 15:32:16 | NULL       | utf8mb4_0900_ai_ci |     NULL |                |         |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
-- The Auto_increment is still 4 (it was cached).

drop schema mytest

Теперь мы изменим конфигурацию:

SET PERSIST information_schema_stats_expiry = 0

и запустим тот же тест:

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';

+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation          | Checksum | Create_options | Comment |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| test | InnoDB |      10 | Dynamic    |    3 |           5461 |       16384 |               0 |            0 |         0 |              4 | 2018-10-09 15:32:49 | 2018-10-09 15:32:49 | NULL       | utf8mb4_0900_ai_ci |     NULL |                |         |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
--  Auto_increment is 4, but the result is not cached!

insert into test values(null,'name3');



show table status where name like 'test';


+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time         | Update_time         | Check_time | Collation          | Checksum | Create_options | Comment |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
| test | InnoDB |      10 | Dynamic    |    4 |           4096 |       16384 |               0 |            0 |         0 |              5 | 2018-10-09 15:32:49 | 2018-10-09 15:32:49 | NULL       | utf8mb4_0900_ai_ci |     NULL |                |         |
+------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------+
-- The  Auto_increment field is now 5 (a correct, not cached value)

drop schema mytest;
...