发表于: lnmp | 作者: | 日期: 2011/9/29 06:09
标签: ,

在调用存储过程中,就会涉及到表锁,行锁这一概念:所谓区别:有索引的时候就是行锁,没有索引的时候就是表索。

innodb 的行锁是在有索引的情况下,没有索引的表是锁定全表的。

表锁演示(无索引)

Session1:


mysql> set autocommit=0;

mysql> select * from innodb_test;
+——+————-+
| id | name |
+——+————-+
| 1 | woshiceshi |
| 2 | woshiceshi2 |
| 3 | woshiceshi3 |
+——+————-+

mysql> select * from innodb_test where id = 2 for update;
+——+————+
| id | name |
+——+————+
| 2 | woshiceshi2 |
+——+————+

Session2:


mysql> update innodb_test set name=’sjis’ where id = 1 ;

处于等待状态….

再回到session1 commit以后,session2就出来结果了(锁定了8秒,过了8秒左右才去session1提交)。


mysql> update innodb_test set name=’sjis’ where id = 1 ;
Query OK, 1 row affected (8.11 sec)
Rows matched: 1 Changed: 1 Warnings: 0

实验结果是:我在session1的for update 操作看似只锁定ID为2的行其实锁定了全表,以至于后面session2的对ID为1的行update 需要等待Session1锁的释放。

行锁演示(索引为ID)

Session1:

mysql> alter table innodb_test add index idx_id(id);
Query OK, 4 rows affected (0.01 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> select * from innodb_test where id = 2 for update;
+——+————+
| id | name |
+——+————+
| 2 | woshiceshi2 |
+——+————+

Session2:


mysql> update innodb_test set name=’wohaishiceshi’ where id = 1 ;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from innodb_test where id = 1;
+——+—————+
| id | name |
+——+—————+
| 1 | wohaishiceshi |
+——+—————+
1 row in set (0.00 sec)

实验结果:这次的锁定是锁定的行,所以没有被锁定的行(ID不为2的行)可以进行update..

来源:http://www.9streets.cn/art-php-377.html

补充说明:

(1)检索条件为主键或索引;(http://www.cublog.cn/u2/69385/showart_1852286.html)
(2)检索条件可以唯一确定一条记录。(http://www.neo.com.tw/archives/900)

: https://blog.darkmi.com/2011/09/29/1998.html

本文相关评论 - 1条评论都没有呢
Post a comment now » 本文目前不可评论

No comments yet.

Sorry, the comment form is closed at this time.