我有一個java應用程序,並且在sql下面發生死鎖異常: insert into voucher ( id, order_id, voucher_code ) SELECT #{id}, #{orderId}, #{voucherCode} FROM DUAL WHERE NOT EXISTS (SELECT id FROM voucher where order_id = #{orderId})
「order_id」是唯一鍵。 我相信當sql在併發執行時它會死鎖。 但是,我沒有足夠的權限來執行show engine innodb status
,所以我無法獲得關於死鎖異常的信息。查找mysql innodb死鎖原因INSERT INTO SELECT
我嘗試在實驗室環境中重現該問題。 臺試驗低於: Create Table: CREATE TABLE `test` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `info` varchar(128) NOT NULL DEFAULT '', `order_id` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `uni_order_id` (`order_id`) ) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8
和我在兩個不同的會話執行兩個sql語句:
insert into test(info,order_id) select '12345',sleep(10) from dual where not exists (select info from test where info='12345');
insert into test(info,order_id) select '12345',234 from dual where not exists (select info from test where info='12345');
僵局日誌如下:
------------------------
LATEST DETECTED DEADLOCK
------------------------
2016-06-20 17:26:54 700000a83000
*** (1) TRANSACTION:
TRANSACTION 2321, ACTIVE 9 sec inserting
mysql tables in use 2, locked 2
LOCK WAIT 5 lock struct(s), heap size 1184, 2 row lock(s)
MySQL thread id 1, OS thread handle 0x700000a3f000, query id 29 localhost root executing
insert into test(info,order_id) select '12345',234 from dual where not exists (select info from test where info='12345')
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 9 page no 3 n bits 72 index `PRIMARY` of table `test`.`test` trx id 2321 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
0: len 8; hex 73757072656d756d; asc supremum;;
*** (2) TRANSACTION:
TRANSACTION 2320, ACTIVE 10 sec setting auto-inc lock
mysql tables in use 2, locked 2
3 lock struct(s), heap size 360, 1 row lock(s)
MySQL thread id 2, OS thread handle 0x700000a83000, query id 28 localhost root User sleep
insert into test(info,order_id) select '12345',sleep(10) from dual where not exists (select info from test where info='12345')
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 9 page no 3 n bits 72 index `PRIMARY` of table `test`.`test` trx id 2320 lock mode S
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
0: len 8; hex 73757072656d756d; asc supremum;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
TABLE LOCK table `test`.`test` trx id 2320 lock mode AUTO-INC waiting
*** WE ROLL BACK TRANSACTION (2)
我假定子查詢select info from test where info=‘12345’
可持有SLOCK ,並且insert into … select
想要XLock。 但我沒有找到官方文件來支持我的觀點。
所以我的問題如下:
1.是我的再現設計權嗎?
2.是我的supposal(subquery select info from test where info=‘12345’
可能會持有SLOCK)對不對?任何官方文件可以支持我的支持?
我想在這種情況下找到死鎖的原因,而不是解決方案。 – FatGhosta