mysql如果主键重复了会发生什么情况


首先创建一个person表:

 

create TABLE `person`(
	`id` int not null auto_increment,
	`name` VARCHAR(255) ,
	`age` int,
	PRIMARY key (`id`)
)

  

 

同时打开两个sql窗口

 

set autocommit=off;

set @id=-1;

SELECT
	auto_increment into @id
FROM
	information_schema.`TABLES`
WHERE
	table_name = 'person'
AND TABLE_SCHEMA = 'test';   -- 第1步运行到这里

INSERT into person(id,name,age) VALUES(@id,'lisi',28);   -- 第3步运行这里

COMMIT;  -- 第5步运行这里(第二种,第4步先运行这里)

  

set autocommit=off;

set @id:=-1;

SELECT
	auto_increment into @id
FROM
	information_schema.`TABLES`
WHERE
	table_name = 'person'
AND TABLE_SCHEMA = 'test';     -- 第2步运行到这里

INSERT into person(id,name,age) VALUES(@id,'wangwu',28);   -- 第4步运行这里(第二种,第5步运行这里)

COMMIT;  -- 第6步运行这里 

  

第一种,运行到第4步的时候,报错了:

[SQL] INSERT into person(id,name,age) VALUES(@id,'wangwu',28);
[Err] 1205 - Lock wait timeout exceeded; try restarting transaction

 

第二种,运行到第5步的时候

[SQL] INSERT into person(id,name,age) VALUES(@id,'wangwu',28);
[Err] 1062 - Duplicate entry '9' for key 'PRIMARY'

 

 

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM