在为一个客户排除死锁问题时我遇到了一个有趣的包括InnoDB间隙锁的情形。对于一个WHERE子句不匹配任何行的非插入的写操作中,我预
mysql> show create table preferences \g
*************************** 1. row ***************************
table: preferences
create table: create table `preferences` (
`numericid` int(10) unsigned not null,
`receivenotifications` tinyint(1) default null,
primary key (`numericid`)
) engine=innodb default charset=latin1
1 row in set (0.00 sec)
mysql> begin;
query ok, 0 rows affected (0.00 sec)
mysql> select count(*) from preferences;
+----------+
| count(*) |
+----------+
| 0 |
+----------+
1 row in set (0.01 sec)
mysql> update preferences set receivenotifications='1' where numericid = '2';
query ok, 0 rows affected (0.01 sec)
rows matched: 0 changed: 0 warnings: 0
InnoDB状态显示这个UPDATE在主索引记录上持有了一个X锁:
---TRANSACTION 4A18101, ACTIVE 12 sec
2 lock struct(s), heap size 376, 1 row lock(s)
MySQL thread id 3, OS thread handle 0x7ff2200cd700, query id 35 localhost msandbox
Trx read view will not see trx with id >= 4A18102, sees TABLE LOCK table `test`.`preferences` trx id 4A18101 lock mode IX
RECORD LOCKS space id 31766 page no 3 n bits 72 index `PRIMARY` of table `test`.`preferences` trx id 4A18101 lock_mode X
这是为什么呢,Heikki在其bug报告中做了解释,这很有意义,我知道修复起来很困难,但略带厌恶地我又希望它能被差异化处理。为完成这篇文章,让我证明下上面说到的死锁情况,下面中mysql1是第一个会话,mysql2是另一个,查询的顺序如下:
mysql1> BEGIN;
Query OK, 0 rows affected (0.00 sec)
mysql1> UPDATE preferences SET receiveNotifications='1' WHERE numericId = '1';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
mysql2> BEGIN;
Query OK, 0 rows affected (0.00 sec)
mysql2> UPDATE preferences SET receiveNotifications='1' WHERE numericId = '2';
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0 Changed: 0 Warnings: 0
mysql1> INSERT INTO preferences (numericId, receiveNotifications) VALUES ('1', '1'); -- This one goes into LOCK WAIT
mysql2> INSERT INTO preferences (numericId, receiveNotifications) VALUES ('2', '1');
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
现在你看到导致死锁是多么的容易,,因此一定要避免这种情况——如果来自于事务的INSERT部分导致非插入的写操作可能不匹配任何行的话,不要这样做,使用REPLACE INTO或使用READ-COMMITTED事务隔离。
推荐阅读:
这是一套由淘掌门(taozhangmen.net)衍生出来的一个拍拍客系统!这套程序也继承了淘掌门的特点:永久免费开源!无任何时间限制、功能限制、域名限制。 程序相对于淘掌门原型,已去除返利、会员系统、文章系统等。 如果需要文章,可单独下载其他的文章系统,做子目录,效果可能会更好。 程序安装过程与淘掌门相同: 下载上传到空间,执行 你的网址/install.php 安装完成后,登陆后台修改拍拍AP
InnoDB存储引擎的启动、关闭与恢复
MySQL InnoDB独立表空间的配置
MySQL Server 层和 InnoDB 引擎层 体系结构图
InnoDB 死锁案例解析
MySQL Innodb独立表空间的配置









