mysql自增值回溯_MySQL5.7之auto_increment回溯

本文通过创建并操作包含自增主键的表t,展示了在MySQL5.7中,删除数据后重启数据库,自增ID会回溯的现象。这是因为MySQL5.7的自增值存储在内存中,而MySQL8.0已解决此问题,实现了自增ID的磁盘持久化。
摘要由CSDN通过智能技术生成

# 创建关于表t,其中a字段为主键自增

mysql> create table t(a bigint primary key auto_increment, b tinyint);

Query OK, 0 rows affected (0.03 sec)

# 插入一些数据

mysql> insert into t select null, 10;

Query OK, 1 row affected (0.00 sec)

Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into t select null, 20;

Query OK, 1 row affected (0.00 sec)

Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into t select null, 30;

Query OK, 1 row affected (0.00 sec)

Records: 1  Duplicates: 0  Warnings: 0

mysql> insert into t select null, 40;

Query OK, 1 row affected (0.00 sec)

Records: 1  Duplicates: 0  Warnings: 0

# 查看表记录

mysql> select * from t;

+---+------+

| a | b    |

+---+------+

| 1 |   10 |

| 2 |   20 |

| 3 |   30 |

| 4 |   40 |

+---+------+

4 rows in set (0.00 sec)

# 删除最后一条数据

mysql> delete from t where a=4;

Query OK, 1 row affected (0.02 sec)

# 查看表创建语句,发现AUTO_INCREMENT=5

mysql> show create table t\G

*************************** 1. row ***************************

Table: t

Create Table: CREATE TABLE `t` (

`a` bigint(20) NOT NULL AUTO_INCREMENT,

`b` tinyint(4) DEFAULT NULL,

PRIMARY KEY (`a`)

) ENGINE=InnoDB

AUTO_INCREMENT=5

DEFAULT CHARSET=latin1

1 row in set (0.00 sec)

# 进行主键回溯模拟

# 重启数据库

[root@mysql ~]# service mysqld restart

Shutting down MySQL.. SUCCESS!

Starting MySQL. SUCCESS!

# 重新查看表创建语句,发现AUTO_INCREMENT=4

mysql> show create table t\G

*************************** 1. row ***************************

Table: t

Create Table: CREATE TABLE `t` (

`a` bigint(20) NOT NULL AUTO_INCREMENT,

`b` tinyint(4) DEFAULT NULL,

PRIMARY KEY (`a`)

) ENGINE=InnoDB

AUTO_INCREMENT=4

DEFAULT CHARSET=latin1

1 row in set (0.00 sec)

# 继续插入语句

mysql> insert into t select null, 50;

Query OK, 1 row affected (0.00 sec)

Records: 1  Duplicates: 0  Warnings: 0

# 查看表的数据,发现上述自增ID=4又重新出现

mysql> select * from t;

+---+------+

| a | b    |

+---+------+

| 1 |   10 |

| 2 |   20 |

| 3 |   30 |

|

4

|   50 |

+---+------+

4 rows in set (0.00 sec)

这是因为在MySQL5.7中的表的AUTO_INCREMENT是基于内存,不会持久化在磁盘中,每次启动数据库时,会对每张表进行max(auto_increment) + 1重新作为该表下一次的主键ID的自增值。在MySQL8.0中就不会出现该问题,因为数据会在磁盘中持久化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值