mysql中的行锁

mysql的行锁跟oracle的行锁不一样的,mysql的行锁基于索引

session A:
test>select * from d;
+——+——+
| id | name |
+——+——+
| 1 | aa |
| 2 | bbb |
+——+——+
2 rows in set (0.00 sec)

test>select * from d where name=’aa’ for update;
+——+——+
| id | name |
+——+——+
| 1 | aa |
+——+——+
1 row in set (0.00 se
session B;

test>update d set id=1111 where name=’bbb’;
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

select * from information_schema.innodb_locks\G;
***************** 1. row *****************
lock_id: 4637:41:3:1
lock_trx_id: 4637
lock_mode: X
lock_type: RECORD
lock_table: test.t5
lock_index: GEN_CLUST_INDEX
lock_space: 41
lock_page: 3
lock_rec: 1
lock_data: supremum pseudo-record
***************** 2. row *****************
lock_id: 4634:41:3:1
lock_trx_id: 4634
lock_mode: X
lock_type: RECORD
lock_table: test.t5
lock_index: GEN_CLUST_INDEX
lock_space: 41
lock_page: 3
lock_rec: 1
lock_data: supremum pseudo-record
2 rows in set (0.01 sec)

ERROR:
No query specified

select * from information_schema.innodb_lock_waits;
+——————-+——————-+—————–+——————+
| requesting_trx_id | requested_lock_id | blocking_trx_id | blocking_lock_id |
+——————-+——————-+—————–+——————+
| 4637 | 4637:41:3:1 | 4634 | 4634:41:3:1 |
+——————-+——————-+—————–+——————
没有索引就是表锁了。加个索引,在操作就不会被阻塞了。我们看到2个事务都是添加了表锁,4637被4634阻塞。下面看下添加非唯一索引引入的gap lock和next-key lock的问题。

你可能感兴趣的:(mysql)