欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mysql中的limit 1 for update的鎖類型

 更新時間:2023年08月29日 16:47:31   作者:luwei9233  
這篇文章主要介紹了mysql中的limit 1 for update的鎖類型,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

mysql limit 1 for update的鎖類型

最近遇到一個業(yè)務問題,購物券號是預先產生的,然后進行客戶ID的綁定,從SQL上來講基本上有兩種方式實現(xiàn)

方式一

begin;
select * from purchase_code where code_type = 0 limit 1 for update;
update purchase_code set code_type=1,user_id=123 where purchase_code_id = 1
commit

方式二

update purchase_code set code_type=1,user_id=123 where code_type=0 limit 1;

之前一直擔心方式一會出現(xiàn)問題;主要是擔心會因為并發(fā)問題,導致選出來的行被其他線程所修改掉,因為一直會覺得第一種方式加的是行鎖,需要查出來繼續(xù)判斷一下code_type才能進行更新。

進行測試了一下發(fā)現(xiàn)上面兩種方式加的都是表鎖。

因為什么原因上面加的是表鎖呢?

經過測試,mysql加鎖有這樣的特點:

主鍵查詢加行鎖

begin;
select * from t_user_role where role_id = "1111" limit 1 for update ;

此時可以對其他行加讀鎖和寫鎖

select * from t_user_role where role_id = 'operator';
select * from t_user_role where role_id = 'operator' for update

鎖升級的情況

role_id為varchar類型,但是用int類型也能搜索出來,但是此時加的是表鎖

select * from t_user_role where role_id = 1111 for update;

當按非主鍵查詢的時候,此時mysql加的是表鎖

此時下面的查詢都會卡住

select * from t_user_role where role_type = 2 limit 1 for update ;
select * from t_user_role where role_id = 'operator' for update;

如果對role_type加上一個key索引,情況就變得有意思

除了最后一次查詢被卡住外,其他查詢全部能返回

select * from t_user_role where role_type = 2 limit 1 for update ;
select * from t_user_role where role_id = 'operator' for update;
select * from t_user_role where role_id = '2222' for update;
select * from t_user_role where role_type = 1 limit 1 for update ;

研究innodb的鎖機制發(fā)現(xiàn)

innodb是通過索引實現(xiàn)行鎖,只有通過索引項查詢的時候,才會加行鎖,否則統(tǒng)一加的是表鎖。

因此role_type上加索引之后,鎖加在了role_type的索引上,從而上面其他三能順利獲得鎖,但是此時已然無法獲取表鎖

mysql update limit 批量修改數(shù)據(jù)

1、想要實現(xiàn)修改數(shù)據(jù)庫的5條之后的數(shù)據(jù)

update demo set flag='1' where user_id=1 limit 5,100;

上面這句測試了是錯誤的,MYSQL的UPDATE語句不能update限制從第N(5)條之后開始更新N(100)條。

2、建議方法

可以改變一下思維方式

  • 1)先將全部flag修改為flag=1; 
  • 2)再按自己需求修改前N條,或者后N條數(shù)據(jù)falg=0;

①、

update demo set flag='1'? where user_id = 1;

②、

修改數(shù)據(jù)前5條:

update demo set flag='1' where user_id=1 and?flag='0'?limit 5;

修改數(shù)據(jù)后5條:

update demo set flag='1' where user_id=1 and?flag='0' order by id desc?limit 5;

總結

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論