douhuangjian9627 2014-11-18 14:09
浏览 321

选择并锁定一行,然后更新UPDATE

I have a script that selects a row from MySQL database. Then updates this row. Like this:

$statement = $db->prepare("SELECT id, link from persons WHERE processing = 0");
$statement->execute();
$row = $statement->fetch();

$statement = $db->prepare("UPDATE persons SET processing = 1 WHERE id = :id");
$success = $statement->execute(array(':id' => $row['id']));

The script calls this php code multiple times simultaneously. And sometimes it SELECTS the row eventhough it should be "processing = 1" because the other script call it at the exact time.

How can I avoid this?

  • 写回答

3条回答 默认 最新

  • doucheng4094 2014-11-18 14:13
    关注

    What you need to do is add some kind of lock here to prevent race conditions like the one you've created:

    UPDATE persons SET processing=1 WHERE id=:id AND processing=0
    

    That will avoid double-locking it.

    To improve this even more, create a lock column you can use for claiming:

    UPDATE persons
      SET processing=:processing_uuid
      WHERE processing IS NULL
      LIMIT 1
    

    This requires a VARCHAR, indexed processing column used for claiming that has a default of NULL. If you get a row modified in the results, you've claimed a record and can go and work with it by using:

    SELECT * FROM persons WHERE processing=:processing_uuid
    

    Each time you try and claim, generate a new claim UUID key.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog