共享锁:
语句后接: lock in share mode
8.0: for share
例:select * from table where id=1for share
排他锁:
语句后接: for update
例:select * from table where id=1for update
修饰词:
nowait:不等待直接报错返回。
skip locked:跳过被锁定的记录,返回未上锁的记录。
例:假设5条记录,事务一锁定了3行,id=(1,2,3)。事务一和事务二至少存在一个x锁。
tx1:
select * from table_a where idin(1,2,3)for update;
tx2:
select * from table_a for share/update; ---阻塞至超时
select * from table_a for share/update nowait; ---直接报错返回
select * from table_a for share/update skip locked; ---返回id为4,5的记录
注意:加锁时条件字段必须有索引,如果全表扫描会给扫描行全部加锁。
表锁语句
查看是否有表锁,in_use字段:
show open tables;
mysql> show open tables;
+--------------------+---------------------------+--------+-------------+
| Database | Table | In_use | Name_locked |
+--------------------+---------------------------+--------+-------------+
| mysql | check_constraints |0|0|| mysql | column_type_elements |0|0|| mysql | slave_master_info |0|0|
加锁:
读锁:lock tables `table_a`read;
写锁:lock tables `table_a`write;
解锁:
unlock tables;
表锁后的操作
全局锁语句
对整个数据库加锁,只读。场景:全库逻辑备份
加锁:
flush tables with read lock;
解锁:
unlock tables;