MySQL插入在不相关的表上持有锁。

问题描述 投票:1回答:1

我从MySQL得到了这个奇怪的死锁。

------------------------
LATEST DETECTED DEADLOCK
------------------------
*** (1) TRANSACTION:
TRANSACTION 2300749061, ACTIVE 1 sec inserting
mysql tables in use 1, locked 1

INSERT INTO `event_entities` ( `entity_id`, `event_id`) VALUES ( '16011341', '8064913' )
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 38454477 page no 22728 n bits 640 index `event_id` of table `event_entities` trx id 2300749061 lock mode S waiting
*** (2) TRANSACTION:
INSERT INTO `account_entities` ( `entity_id`, `account_id`) VALUES ( '16093815', '4590372' )
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 38454477 page no 22728 n bits 640 index `event_id` of table `event_entities` trx id 2300748502 lock_mode X locks rec but not gap
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 38454560 page no 21704 n bits 896 index `account_id` of table `account_entities` trx id 2300748502 lock mode S waiting
*** WE ROLL BACK TRANSACTION (1)

这些表是这样的

CREATE TABLE `event_entities` (
  `event_id` int(11) NOT NULL,
  `entity_id` int(11) NOT NULL,
  PRIMARY KEY (`event_id`,`entity_id`),
  KEY `entity_id` (`entity_id`),
  CONSTRAINT `event_entities_fk_1` FOREIGN KEY (`event_id`) REFERENCES `events` (`event_id`) ON UPDATE CASCADE,
  CONSTRAINT `event_entities_fk_2` FOREIGN KEY (`entity_id`) REFERENCES `entities` (`entity_id`) ON UPDATE CASCADE
)
CREATE TABLE `account_entities` (
  `account_id` int(11) NOT NULL,
  `entity_id` int(11) NOT NULL,
  PRIMARY KEY (`account_id`,`entity_id`),
  KEY `entity_id` (`entity_id`),
  CONSTRAINT `account_entities_fk_1` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`account_id`) ON UPDATE CASCADE,
  CONSTRAINT `account_entities_fk_2` FOREIGN KEY (`entity_id`) REFERENCES `entities` (`entity_id`) ON UPDATE CASCADE
)

我不明白为什么插入account_entities会锁住event_entities 但我肯定这和这两张表都有FK到实体有关。谁能解释一下可能发生了什么?

mysql innodb deadlock
1个回答
0
投票

很有可能是事务2中较早的一个查询,是创建锁的index event_id 的表 event_entities.

请启用general_log,并在事务中发布所有SQL语句。

© www.soinside.com 2019 - 2024. All rights reserved.