mysql> create table test(id int,nick varchar(32)) engine=innodb ;
Query OK, 0 rows affected (0.05 sec)
mysql>
mysql>
mysql> set autocommit=off;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into test values(1,'a');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(2,'b');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(3,'c');
Query OK, 1 row affected (0.00 sec)
mysql> insert into test values(4,'d');
Query OK, 1 row affected (0.00 sec)
mysql> commit;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from test;
+------+------+
| id | nick |
+------+------+
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
+------+------+
4 rows in set (0.00 sec)
mysql>
mysql>
mysql> update test set nick='lock_a' where id=1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
--session 2
mysql> select * from test;
+------+------+
| id | nick |
+------+------+
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
+------+------+
4 rows in set (0.00 sec)
mysql> update test set nick='lock_b' where id=2;
Query OK, 1 row affected (1 min 29.90 sec) --等待很长的时间,直到session 1提交为止
Rows matched: 1 Changed: 1 Warnings: 0
mysql> commit;
Query OK, 0 rows affected (0.00 sec)
mysql> select * from test;
+------+--------+
| id | nick |
+------+--------+
| 1 | lock_a |
| 2 | lock_b |
| 3 | c |
| 4 | d |
+------+--------+
4 rows in set (0.00 sec)
如果在test表的id列上创建索引,再观察一下加锁情况
--session 1
mysql> create unique index uk_test_id on test(id);
Query OK, 4 rows affected (0.07 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql>
mysql> update test set nick='lock_aa' where id=1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
更新后,但并不提交,执行session 2的更新语句,发现立刻执行完
--session 2
mysql> update test set nick='lock_bb' where id=2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
--session 1,session 2
mysql> commit;
Query OK, 0 rows affected (0.00 sec)