2013-10-22 74 views
0

我試圖做與MySQL: Insert record if not exists in table中描述的相同的事情,但我在命令行上運行它,所以我需要手動鎖定表。這是我有:鎖定「本地」MySQL表

LOCK TABLES `mytable` WRITE; 
INSERT INTO `mytable` (`mycolumn`) 
SELECT * FROM (SELECT 'test') AS temp 
WHERE NOT EXISTS ( 
    SELECT `mycolumn` 
    FROM `mytable` 
    WHERE `mycolumn` = 'test' 
) LIMIT 1; 
UNLOCK TABLES; 

然而,當我運行此我得到的錯誤:

ERROR 1100 (HY000) at line 239: Table 'mytable' was not locked with LOCK TABLES 

的命令執行罰款不鎖定/解鎖在MySQL工作臺。我的猜測是我需要鎖定「臨時」表,但我該怎麼做?

LOCK TABLES `mytable` WRITE, <something> AS temp WRITE; 

由於「temp」不是數據庫中的實際表,它只是(SELECT'test')。

我可以補充一點,我沒有(只是)想創建一個唯一索引的原因是,這導致了一個錯誤,我不知道如何處理,因爲命令行進程的退出代碼是總是隻有1,如果出現錯誤,我真的不想解析stderr ...

+0

是'萬一臨時表mytable'?發佈輸出:show create table mytable'; – Cillier

+0

MYTABLE,CREATE TABLE'mytable'( 'id' INT(11)NOT NULL AUTO_INCREMENT, 'value' VARCHAR(10)字符集UTF8 NOT NULL, PRIMARY KEY('id') )ENGINE = InnoDB的AUTO_INCREMENT = 82 DEFAULT CHARSET = utf8 COLLATE = utf8_swedish_ci – moggizx

回答

1

此行爲在LOCK TABLES的MySQL手冊頁中有詳細記錄;

http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html

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:

所以,這應該爲你工作:

LOCK TABLES `mytable` WRITE, `mytable` as m2 READ 
INSERT INTO `mytable` (`value`) SELECT * FROM (SELECT 'test') AS temp 
WHERE NOT EXISTS ( 
    SELECT `value` 
    FROM `mytable` as `m2` 
    WHERE `value` = 'test' 
) LIMIT 1; 
UNLOCK TABLES;