CREATE TABLE `author` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`author_id` varchar(50) NOT NULL DEFAULT '' COMMENT '作者號(hào)',
`author_name` varchar(50) NOT NULL DEFAULT '' COMMENT '作者名',
`content` varchar(255) NOT NULL DEFAULT '' COMMENT '作者簡(jiǎn)介',
PRIMARY KEY (`id`),
KEY `idx_content` (`content`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COMMENT='作者表'
id | author_id | author_name | content |
---|---|---|---|
1 | 0001 | 張三 | 222 |
2 | 0002 | 李四 | 222 |
3 | 0003 | 王五 | 222 |
其中id為主鍵产场,content為普通索引
session1 | session2 |
---|---|
start transaction; | start transaction; |
update author set author_name = '5555' where id = 1;(持有id為1的行鎖) | |
update author set author_name = '8888' where content = '222';(獲取idx_content的鎖浙巫,然后繼續(xù)嘗試獲取id為1、2、3三行的行鎖,由于事務(wù)1已經(jīng)獲取了id為1的行鎖。所以這里會(huì)阻塞) | |
update author set author_name = '999' where content = '222';(嘗試獲取idx_content的鎖传于,與事務(wù)2死鎖) | |
ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction | |
commit盐欺; | commit座泳; |
由于事務(wù)1最后提交了一個(gè)修改sql城侧。因此事務(wù)1的修改會(huì)生效浓瞪,事務(wù)2會(huì)報(bào)異常并回滾。
mysql加鎖過(guò)程參考文章:https://www.cnblogs.com/xiaohuangya/articles/3552990.html