官网地址:https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html
A session that requires locks must acquire all the locks that it needs in a single LOCK TABLES
statement. While the locks thus obtained are held, the session can access only the locked tables. For example, in the following sequence of statements, an error occurs for the attempt to access t2
because it was not locked in the LOCK TABLES
statement:
mysql> LOCK TABLES t1 READ;
mysql> SELECT COUNT(*) FROM t1;
+----------+
| COUNT(*) |
+----------+
| 3 |
+----------+
mysql> SELECT COUNT(*) FROM t2;
ERROR 1100 (HY000): Table 't2' was not locked with LOCK TABLES
Tables in the INFORMATION_SCHEMA
database are an exception. They can be accessed without being locked explicitly even while a session holds table locks obtained with LOCK TABLES
.
You cannot refer to a locked table multiple times in a single query using the same name. Use aliases instead, and obtain a separate lock for the table and each alias:
mysql> LOCK TABLE t WRITE, t AS t1 READ;
mysql> INSERT INTO t SELECT * FROM t;
ERROR 1100: Table 't' was not locked with LOCK TABLES
mysql> INSERT INTO t SELECT * FROM t AS t1;
The error occurs for the first INSERT
because there are two references to the same name for a locked table. The second INSERT
succeeds because the references to the table use different names.
If your statements refer to a table by means of an alias, you must lock the table using that same alias. It does not work to lock the table without specifying the alias:
mysql> LOCK TABLE t READ;
mysql> SELECT * FROM t AS myalias;
ERROR 1100: Table 'myalias' was not locked with LOCK TABLES
Conversely, if you lock a table using an alias, you must refer to it in your statements using that alias:
mysql> LOCK TABLE t AS myalias READ;
mysql> SELECT * FROM t;
ERROR 1100: Table 't' was not locked with LOCK TABLES
mysql> SELECT * FROM t AS myalias;
问题分析:你在一个session里面lock table锁表,你只能访问你锁的那张表;访问其他表,就报这个异常。例如你lock table ‘t’ read,然后你select t2,此时t2就会报这个异常。
解决方法:
- 一次性拿到你需要访问的表锁:A session that requires locks must acquire all the locks that it needs in a single
LOCK TABLES
statement. - unlock tables释放session已经持有的表锁,再访问其他表。