MySQL锁表的目的 MySQL enables client sessions to acquire table locks explicitly(明白地,明确地) for the purpose of cooperating with other sessions for access to tables, or to prevent other sessions from modifying tables during periods when a session requires exclusive(单独的,排外的) access to them. A session can acquire or release locks only for itself.One session cannot acquire locks for another session or release locks held by another session.
LOCK TABLES LOCK TABLES explicitly acquires table locks for the current client session. Table locks can be acquired for base tables or views. You must have the LOCK TABLES privilege, and the SELECT privilege for each object to be locked.
For view locking, LOCK TABLES adds all base tables used in the view to the set of tables to be locked and locks them automatically.If you lock a table explicitly with LOCK TABLES, any tables used in triggers are also locked implicitly.
UNLOCK TABLES UNLOCK TABLES explicitly(明确的) releases any table locks held by the current session. LOCK TABLES implicitly(隐式的) releases any table locks held by the current session before acquiring new locks.
Another use for UNLOCK TABLES is to release the global read lock acquired with the FLUSH TABLES WITH READ LOCK statement, which enables you to lock all tables in all databases.
WRITE LOCK 和 READ LOCK的作用 A table lock only protects against inappropriate(不恰当的,不合适的) reads or writes by other sessions. A session holding a WRITE lock can perform table-level operations such as DROP TABLE or TRUNCATE TABLE.For sessions holding a READ lock, DROP TABLE and TRUNCATE TABLE operations are not permitted. TRUNCATE TABLE operations are not transaction-safe, so an error occurs if the session attempts one during an active transaction or while holding a READ lock.
mysql> drop table people;
ERROR 1099 (HY000): Table 'people' was locked with a READ lock and can't be updated
mysql> truncate people;
ERROR 1099 (HY000): Table 'people' was locked with a READ lock and can't be updated
mysql>