回滚事务对自增字段的影响

-- 创建表
DROP TABLE IF EXISTS `prefix_user`;
CREATE TABLE `prefix_user`
(
    `uid`  int unsigned NOT NULL AUTO_INCREMENT COMMENT '用户UID',
    `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '用户姓名',
    PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';


-- 开启事务
BEGIN;


INSERT INTO `prefix_user` SET `name` = '刘一';
INSERT INTO `prefix_user` SET `name` = '陈二';
INSERT INTO `prefix_user` SET `name` = '张三';


-- 回滚事务
ROLLBACK;


-- 开启事务
BEGIN;


INSERT INTO `prefix_user` SET `name` = '李四';
INSERT INTO `prefix_user` SET `name` = '王五';
INSERT INTO `prefix_user` SET `name` = '赵六';


-- 提交事务
COMMIT;


SELECT `uid`, `name` FROM `prefix_user`;
-- +-----+--------+
-- | uid | name   |
-- +-----+--------+
-- |   4 | 李四   |
-- |   5 | 王五   |
-- |   6 | 赵六   |
-- +-----+--------+
-- 3 rows in set (0.00 sec)


---------- 总结 ----------
-- 1、只要INSERT语句执行成功,不管事务回不回滚,自增值都已经被使用掉了。

Copyright © 2024 码农人生. All Rights Reserved