我的表的定义类似于:
CREATE TABLE `test_table` (
`a` int,
`b` int,
PRIMARY KEY (`a`),
UNIQUE KEY `idx_b` (`b`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
并且隔离级别为:已提交读(RC)
并且查询sql类似于:update test_table set a=LAST_INSERT_ID(a + 1) WHERE b= 1;
[当多个客户端请求同时执行相同的SQL时,mysql可能会发生死锁错误,并且死锁日志类似于:
------------------------
LATEST DETECTED DEADLOCK
------------------------
2020-05-26 18:04:12 0x7efb06c5d700
*** (1) TRANSACTION:
TRANSACTION 261901143, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 1136, 1 row lock(s)
MySQL thread id 6018875, OS thread handle 139617907197696, query id 3320727857 10.202.6.165 ma88 updating
update test_table set a=LAST_INSERT_ID(a + 1) WHERE b=1
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 6485 page no 4 n bits 272 index idx_b of table test_db.test_table trx id 261901143 lock_mode X locks rec but not gap waiting
Record lock, heap no 148 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 1; hex 06; asc ;;
1: len 4; hex 00aeae62; asc b;;
*** (2) TRANSACTION:
TRANSACTION 261901142, ACTIVE 0 sec updating or deleting, thread declared inside InnoDB 4999
mysql tables in use 1, locked 1
4 lock struct(s), heap size 1136, 3 row lock(s), undo log entries 2
MySQL thread id 6018874, OS thread handle 139616615520000, query id 3320727856 10.202.6.165 ma88 updating
update test_table set a=LAST_INSERT_ID(a + 1) WHERE b=1
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 6485 page no 4 n bits 272 index idx_b of table test_db.test_table trx id 261901142 lock_mode X locks rec but not gap
Record lock, heap no 148 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 1; hex 06; asc ;;
1: len 4; hex 00aeae62; asc b;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 6485 page no 4 n bits 272 index idx_b of table test_db.test_table trx id 261901142 lock mode S waiting
Record lock, heap no 148 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 1; hex 06; asc ;;
1: len 4; hex 00aeae62; asc b;;
*** WE ROLL BACK TRANSACTION (1)
通过此死锁日志,我发现:事务1正在等待事务2持有的X锁,事务2希望对同一数据使用S锁,然后再进行死锁。
我不明白的是为什么在这种情况下,transaction-2想要一个S Lock却同时持有一个X Lock。
有人可以给我一个答案或想法吗?
考虑将UPDATE
拉出事务。它可能会导致“燃烧”某些序列号。