I have table
tasks
id, started_at, ...
1, 2017-01-01 10:00:00
2, 2017-01-01 10:00:00
3, NULL
4, NULL
...
SELECT * FROM TASKS WHERE started_at IS NULL LIMIT 10
save ids of above query to ids variable
UPDATE tasks SET started_at = <<NOW>> WHERE id IN <<ids>>
Now I need to make sure that no other process reads the same ids before the update has happened.
I tried:
START TRANSACTION;
SELECT * FROM tasks WHERE requested_at IS NULL LOCK IN SHARE MODE;
and
START TRANSACTION;
SELECT * FROM tasks WHERE requested_at IS NULL FOR UPDATE;
However I still got the same resultset when querying from another connection even though I have not finished the transaction.
答案 0 :(得分:0)
我认为UPDATE
是应该发生锁定的地方,因为这是您不希望其他人查询并找回不完整/不一致数据的点。因此,您可以尝试执行UPDATE
,如下所示:
LOCK TABLES tasks WRITE;
UPDATE tasks SET started_at = <<NOW>> WHERE id IN <<ids>>
UNLOCK TABLES;
另一种选择是在事务中执行更新:
START TRANSACTION;
UPDATE tasks SET started_at = <<NOW>> WHERE id IN <<ids>>
COMMIT;
在任何一种情况下,在UPDATE
完成之前,其他任何人都无法访问正在更新的记录。