Yii: MySql - Table 'card' was not locked with LOCK TABLES
遇到标题上面的错误信息,通常是因为某个进程锁了表1,在没有释放锁时,想要访问另外一个表2,
这个在mysql中是不允许的,该错误信息的含义很明白,表card没有被锁,所以不能执行查询或更新语句。
详细解释参见mysql手册:
A session that requires locks must acquire all the locks that it needs in a single LOCK TABLES statement.
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
但实际代码是已经锁住了该user表,如下所示:
$lock = Yii::app()->db->createCommand("lock tables card write")->execute();
$card = Card::model()->find('card_no=:card_no AND password=:password',array(':card_no'=>$card,':password'=>$pwd));
那为什么还报这个错误呢? 原因是Yii在使用AR的时候,实际生成的sql语句,使用了别名“t”, 被mysql当作了不同的表,那么按照mysql手册的说明,这是不允许的。
[注意]:lock tables 语句不能使用queryAll来执行,要用execute,否则没有锁成功。
把代码修改为直接用sql查询即可:
$lock = Yii::app()->db->createCommand("lock tables card write")->execute();
$sql = "Select * From card Where `card_type`=0 order By rand() Limit 1";
$result = Yii::app()->db->createCommand( $sql)->queryAll();
if(!$result){
$unlock = Yii::app()->db->createCommand("unlock tables")->execute();
return 0;
--转自