gpt4 book ai didi

mysql - 锁定 "local"MySQL 表

转载 作者:行者123 更新时间:2023-11-29 13:30:36 26 4
gpt4 key购买 nike

我正在尝试执行 MySQL: Insert record if not exists in table 中描述的相同操作,但我在命令行上运行它,所以我需要手动锁定表。这就是我所拥有的:

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 Workbench 中无需锁定/解锁即可正常执行。我的猜测是我需要锁定“临时”表,但我该怎么做?

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

由于“temp”不是数据库中的实际表,它只是 (SELECT 'test')。

我可以补充一点,我不想(只是)创建唯一索引的原因是,这会导致一个我不知道如何处理的错误,因为命令行进程的退出代码始终是只是 1 以防出现错误,我真的不想为它解析 stderr...

最佳答案

这种行为在 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;

关于mysql - 锁定 "local"MySQL 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19519026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com