两个insert之间发生死锁的例子

本文通过实例分析了MySQL中两个INSERT语句导致死锁的原因,涉及行锁、唯一性检查和死锁信息的解读,强调了在特定情况下,即使没有唯一键冲突,也可能发生死锁,并探讨了ON DUPLICATE KEY UPDATE语句在死锁中的角色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为什么没有产生唯一键冲突报错?因为还没获得行锁,无法判断唯一性
一、简单insert之间的死锁
测试表:

mysql> select * from sam;
+----+------+------+
| id | col1 | col2 |
+----+------+------+
|  1 |    1 |    1 |
|  2 |    2 |    2 |
|  3 |    3 |    3 |
+----+------+------+
3 rows in set (0.00 sec)

mysql> desc sam;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
| col1  | int(11) | YES  | UNI | NULL    |       |
| col2  | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

会话1,执行insert,不提交

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into sam values (4,5,5);
Query OK, 1 row affected (0.00 sec)

会话2,执行insert,由于id=4已被会话1上了行锁,所以被堵塞

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into sam values (4,5,5);

会话2,执行insert,由于id=4已被会话1上了行锁,所以被堵塞

mysql> begin;
Query OK, 0 rows affected (0.00 sec)

mysql> insert into sam values (4,5,5);

此时的事务锁等待信息:

---TRANSACTION 69992, ACTIVE 3 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 1136, 1 row lock(s)
MySQL thread id 5, OS thread handle 140302983333632, query id 275 localhost sam update
insert into sam values (4,5,5)
------- TRX HAS BEEN WAITING 3 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 76 page no 3 n bits 80 index PRIMARY of table `sam`.`sam` trx id 70015 lock mode S locks rec but not gap waiting
Record lock, heap no 13 PHYSICAL RECORD: n_fields 5; compact format; info bits 0
 0: len 4; hex 80000004; asc     ;;
 1: len 6; hex 00000001117d; asc      };;
 2: len 7; hex d60000015f0110; asc     _  ;;
 3: len 4; hex 80000005; asc     ;;
 4: len 4; hex 80000005; asc     ;;

------------------
---TRANSACTION 69991, ACTIVE 10 sec inserting
mysql tables in use 1, locked 1
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值