InnoDB下,自增键的机制,真的搞透彻了吗?可以尝试回答一下以下四个问题。 实验一、自增键初始值测验
drop table t1;
create table t1(
id int not null auto_increment,
name varchar(10) unique,
count int default 0,
primary key(id),
index(name)
)engine=innodb;
insert into t1(name) values("zhangsan"),("lisi"),("wangwu");
select from t1;
画外音:初始值,是0还是1? 实验二、批量插入测验
drop table t1,t2;
create table t1(
id int not null auto_increment,
name varchar(10) unique,
count int default 0,
primary key(id),
index(name)
)engine=innodb;
create table t2(
name varchar(10) unique
)engine=innodb;
insert into t2(name) values("x"),("y"),("z");
insert into t1(name) select name from t2;
select from t1;
create table t1(
id int not null auto_increment,
name varchar(10) unique,
count int default 0,
primary key(id),
index(name)
)engine=innodb;
insert into t1(id, name) values(1, "shenjian");
insert into t1(id, name) values (111, "111"),(NULL, "abc"),(222, "222"),(NULL,"xyz");
select from t1; 请问,最后一个insert语句,执行结束后id分别是:A 1,2,3,111,222B 1,111,112,222,223C 插入失败,自增键报错D 以上都不对 实验四、insert ... on duplicate key测验接着实验三,继续执行以下语句:
insert into t1(name)values("shenjian"),("aaa"),("bbb")
on duplicate key update count=100;
select from t1;
请问,最后一个insert语句,执行结束后id分别是:A 1,2,3,111,222,223,224,225B 1,111,112,222,223,224,225,226C 1,111,112,222,223,224,225D 1,111,112,222,223,225,226E 以上都不对 很多时候,我们只是以为自己懂了。画外音:做实验之前,版本先拉平到MySQL5.6。 更复杂的问题是:InnoDB在并发插入情况下,自增键的锁机制是怎样的?画外音:(1)行锁还是表锁?
(2)事务范围加锁还是SQl语句范围加锁?
本文转自“架构师之路”公众号,58沈剑提供。