1.唯一键冲突
比如increnment_test中已经存在了co1为3的记录,当再插入col1为3的记录时,就会出现主键不唯一错误,但此时自增主键已经+1,所以会发生主键不连续情况
DROP TABLE IF EXISTS `increnment_test`;
CREATE TABLE `increnment_test` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`col1` int(0) NULL DEFAULT NULL,
`col2` int(0) NULL DEFAULT NULL,
`col3` int(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uni_col1`(`col1`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
INSERT INTO `mytest`.`increnment_test`(`id`, `col1`, `col2`, `col3`) VALUES (1, 1, 1, 1);
INSERT INTO `mytest`.`increnment_test`(`id`, `col1`, `col2`, `col3`) VALUES (2, 2, 2, 2);
INSERT INTO `mytest`.`increnment_test`(`id`, `col1`, `col2`, `col3`) VALUES (3, 3, 3, 3);
INSERT INTO `mytest`.`increnment_test`(`col1`, `col2`, `col3`) VALUES (3, 3, 3);
INSERT INTO `mytest`.`increnment_test`(`col1`, `col2`, `col3`) VALUES (3, 3, 3);
INSERT INTO `mytest`.`increnment_test`(`col1`, `col2`, `col3`) VALUES (4, 4, 4);
2.事务回滚
开启一个事务,插入col1为6的记录,然后进行回滚.回滚后重新插入col1为6的记录,此时col1为6的记录,对应的id值为7,原理同唯一键冲突一致
BEGIN;
INSERT INTO `mytest`.`increnment_test`(`col1`, `col2`, `col3`) VALUES (6,6,6);
ROLLBACK;
BEGIN;
INSERT INTO `mytest`.`increnment_test`(`col1`, `col2`, `col3`) VALUES (6,6,6);
COMMIT;
3.批量插入语句
对于批量插入数据的语句,mysql有一个批量申请自增id 的策略,同一个语句去申请自增id,每次申请到的自增id个数都是上一次的两倍
即, 第一次申请会分配1个id
第二次申请会分配2个id
第三次申请会分配4个id
因批量申请策略的存在,所以也会造成自增主键不连续
DROP TABLE IF EXISTS `increnment_test2`;
CREATE TABLE `increnment_test2` (
`id` int(0) NOT NULL AUTO_INCREMENT,
`col1` int(0) NULL DEFAULT NULL,
`col2` int(0) NULL DEFAULT NULL,
`col3` int(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `uni_col1`(`col1`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
INSERT INTO increnment_test2(col1,col2,col3)
SELECT col1,col2,col3 FROM increnment_test;
INSERT INTO increnment_test2(col1,col2,col3) VALUES(8,8,8);
SELECT * FROM increnment_test2;