一個InnoDB 加鎖的案例

來源:互聯網
上載者:User

最近一直在最佳化各個產品的SQL語句,同時還幫一個同事解決deadlock問題,收穫就是對InnoDB加鎖的理解更加深入了。先來看看今天的這個案例:

  1. mysql> select version();
  2. +----------------------+
  3. | version() |
  4. +----------------------+
  5. | 5.5.13.4-log |
  6. +----------------------+
  7. mysql> show variables like'%iso%';
  8. +---------------+-----------------+
  9. | Variable_name | Value |
  10. +---------------+-----------------+
  11. | tx_isolation | REPEATABLE-READ |
  12. +---------------+-----------------+
  13. CREATETABLE `t1` (
  14. `a` int(11) NOTNULL,
  15. `b` int(11) DEFAULTNULL,
  16. `c` int(11) DEFAULTNULL,
  17. PRIMARYKEY (`a`)
  18. ) ENGINE=InnoDB;
  19. mysql> select * from t1;
  20. +----+------+------+
  21. | a | b | c |
  22. +----+------+------+
  23. | 1 | 1 | 1 |
  24. | 2 | 1 | 1 |
  25. | 3 | 1 | 1 |
  26. | 10 | 1 | 1 |
  27. | 11 | 1 | 1 |
  28. | 12 | 1 | 1 |
  29. | 14 | 1 | 1 |
  30. | 15 | 1 | 1 |
  31. +----+------+------+

測試環境就是如上,開始下面的測試:

  1. session1:
  2. mysql> begin;
  3. Query OK, 0 rows affected (0.00 sec)
  4. mysql> select * from t1 where a in (2, 10, 11, 12,14) forupdate;
  5. +----+------+------+
  6. | a | b | c |
  7. +----+------+------+
  8. | 2 | 1 | 1 |
  9. | 10 | 1 | 1 |
  10. | 11 | 1 | 1 |
  11. | 12 | 1 | 1 |
  12. | 14 | 1 | 1 |
  13. +----+------+------+
  14. 5 rowsinset (0.00 sec)

 

  1. session2:
  2. mysql> insertinto t1 values(7, 1, 1);
  3. ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
  4. mysql> select * from t1 where a=15 forupdate;
  5. ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
  6. mysql> insertinto t1 values(18,1,1);
  7. ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
  8. mysql> insertinto t1 values(18000,1,1);
  9. ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

從上面可以看出InnoDB彷彿是將[2, 無窮大)這個區間給鎖了,那麼原因是什麼呢? 你可以先思考下

  • 1
  • 2
  • 下一頁

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.