使用“替换为”语句时,MySQL死锁发生在唯一键中

时间:2019-04-13 12:27:14

标签: mysql database transactions locking b-tree

总结问题

当在多个语句中同时执行“替换为model_test值(1,abc,111)”语句和“替换为model_test值(2,abcd,123)”语句时,会发生死锁问题。线程环境。

显示一些代码

在生产环境中,像这样的表(简化):

id name  value
1  abc   111
2  abcd  123

创建表语句为:

CREATE TABLE `db_research`.`model_test` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(45) NULL,
  `value` INT(11) NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `name_UNIQUE` (`name` ASC));

当我执行show engine innodb status时,我们可以看到有关“最新检测到的死锁”的一些信息

提供背景,包括您已经尝试过的内容

MySQL版本:8.0.11

我试图将replace into语句拆分为delete语句和insert语句。

transaction2:

mysql>begin;
mysql>delete from model_test where id = 2;
Query OK,1 row affected(0.02 sec)

transaction1:

mysql>begin;
mysql>replace into model_test values(1,'abc',111);
(waiting...)

transaction2:

mysql>insert into model_test values(2,'abcd',123);
Query OK,1 row affected(0.08 sec)

transaction1:

ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction

show engine innodb status :

*** (1) TRANSACTION:
LOCK WAIT 4 lock struct(s), heap size 1136, 3 row lock(s), undo log entries 2
replace into model_test values(1,'abc','111')
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 3565 page no 4 n bits 72 index name_UNIQUE of table `db_research`.`model_test` trx id 1238711 lock_mode X waiting

*** (2) TRANSACTION:
5 lock struct(s), heap size 1136, 4 row lock(s), undo log entries 2
insert into model_test values(2,'abcd','123')
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 3565 page no 4 n bits 72 index name_UNIQUE of table `db_research`.`model_test` trx id 1238710 lock_mode X locks rec but not gap

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 3565 page no 4 n bits 72 index name_UNIQUE of table `db_research`.`model_test` trx id 1238710 lock mode S waiting

*** WE ROLL BACK TRANSACTION (1)

是由于MySQL对唯一键的下一键锁定吗?

0 个答案:

没有答案