MySQL8.0的锁定读(for share、for update、NOWAIT、skip locked) 和 非锁定读

I.基础定义

MySQL InnoDB 事务模型中读取分为:
1.Consistent Nonlocking Reads(一致性非锁定读)
2.Locking Reads(锁定读)


II.Consistent Nonlocking Reads(一致性非锁定读)


A consistent read means that InnoDB uses multi-versioning to present to a query a snapshot of the database at a point in time.
简单来说就是我们平时普通的SQL查询

SELECT * FROM `testid` where id =180;


II.Locking Reads(锁定读)


If you query data and then insert or update related data within the same transaction, the regular SELECT statement does not give enough protection. Other transactions can update or delete the same rows you just queried. InnoDB supports two types of locking reads that offer extra safety:
SELECT ... FOR SHARE
SELECT ... FOR UPDATE


普通SELECT 语句无法提供足够的保护。其他事务可以更新或删除您刚刚查询的相同行。额外提供了for share和 for update 两种锁定读。

SELECT * FROM `testid` where id =180 for share ;
SELECT * FROM `testid` where id =180 for UPDATE ;

III.提高锁定读的并发性


If a row is locked by a transaction, a SELECT ... FOR UPDATE or SELECT ... FOR SHARE transaction that requests the same locked row must wait until the blocking transaction releases the row lock.
如果想要锁定读的数据正在被锁定,则当前事务必须阻塞等待,直到其他事务释放行锁。

提供两种方式来避免阻塞:NOWAIT 、SKIP LOCKED


1.NOWAIT 
如果请求的行被锁定,则失败并出现错误。

[Err] 3572 - Statement aborted because lock(s) could not be acquired immediately and NOWAIT is set.

2.SKIP LOCKED
发现行被锁定,就跳过该条数据。
 

I.实验数据库基础信息


CREATE TABLE `testid` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '自增主键',
  `user_id` varchar(50) DEFAULT NULL COMMENT '用户Id',
  `update_time` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ;



INSERT INTO `testid` VALUES ('180', 'aaa', '2021-03-01 0
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dingsai88

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值