自增主键其实就是序列 获取下一个序列都是在执行插入之前。在不知道执行是否能够成功的时候 mysql 已经查询出了本次需要使用的主键ID 自然数据插入失败主键也就增加一次。假如你想要插入失败id不自增你可以给序列也加上事务(这样或导致本次插入未结束 其余需要获取该序列的操作 全部等待)
那这种情况是否推荐加上事物呢?
也谢谢您了
@我也是不会飞的猪: 不推荐加。mysql 和oracle 设计的应该也是不能加的。
@xiyanya: 谢谢您了
我知道是因为自增主键,但是为甚他即使没成功添加数据那个主键也会自增,我没搞懂,我是新人菜鸟,请别见怪,谢谢。
@我也是不会飞的猪: 这个机制是只要呼叫一次自增主键就会 + 1 , 所以就算有异常也不会回滚 , 这是自增主键的特性
@我问故我在: 谢谢您
http://sqlines.com/mysql/auto_increment
-- Define a table with an auto-increment column (id starts at 100)
CREATE TABLE airlines
(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(90)
)
AUTO_INCREMENT = 100;
-- Insert a row, ID will be automatically generated
INSERT INTO airlines (name) VALUES ('United Airlines');
-- Get generated ID
SELECT LAST_INSERT_ID();
-- Returns: 100
Overview:
Start Value Default is 1
Increment Always 1
How to Generate IDs Omit the AUTO_INCREMENT column in INSERT, or specify NULL or 0
Explicit ID Insert
Restrictions Only one AUTO_INCREMENT column per table
Primary key or unique must be specified
DEFAULT is not allowed
Last ID LAST_INSERT_ID returns the last value inserted in the current session
LAST_INSERT_ID returns ID for the first successfully inserted row in multi-row INSERT
Gaps If a value larger than the current max ID value is explicitly inserted,
then new IDs with start from this value + 1
Restart (Reset) ALTER TABLE table_name AUTO_INCREMENT = new_start_value;
Version: MySQL 5.6
MySQL AUTO_INCREMENT Details
To generate a ID value, you can omit the auto-increment column in INSERT statement, or specify NULL or 0 value explicitly:
-- Omit auto-increment column
INSERT INTO airlines (name) VALUES ('Delta');
-- Specify NULL or 0
INSERT INTO airlines VALUES (NULL, 'Southwest');
INSERT INTO airlines VALUES (0, 'American Airlines');
Make a Gap
You can insert an ID value explicitly, then MySQL will generate new IDs starting from it adding 1:
INSERT INTO airlines VALUES (200, 'Lufthansa');
INSERT INTO airlines (name) VALUES ('British Airways'); -- id 201 is assigned
You can still insert inside the gap using ID less than the current maximum ID, but this does not affect ID that will be used for other rows:
INSERT INTO airlines VALUES (150, 'Air France'); -- id 150 inserted
INSERT INTO airlines (name) VALUES ('KLM'); -- id 202 is assigned
也谢谢您,虽然我没完全看懂