温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MySQL数据库auto_increment自增值回溯

发布时间:2021-09-04 14:09:58 来源:亿速云 阅读:120 作者:chen 栏目:MySQL数据库

本篇内容介绍了“MySQL数据库auto_increment自增值回溯”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

# 创建关于表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中就不会出现该问题,因为数据会在磁盘中持久化。

“MySQL数据库auto_increment自增值回溯”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI