dongtuo5611 2017-01-11 23:03
浏览 34
已采纳

正确处理并行插入PHP / MySQL

I have a PHP app which receives information from an external source, and saves data to MySQL.

The algorithm is very simple. The data being sent is a string, and it works this way:

  1. Receive the data in $data. Ex: $data = "info"
  2. Checks in database if "info" exists. Ex: select count(*) from table where data="info"
  3. If "info" exists, then exit
  4. Else insert "info" in database and exit.

When there are several parallel requests to the page, there are some duplicates. The data can be sent twice of more times, but we need to save it just once.

The reason is that there's a time lapse between the steps 2 and 3, where the data is still not inserted, so two instances can insert it at the same time.

What's the correct way to handle this in PHP?

(The idea is not to add a unique index to MySQL, I know it'll work but will throw an error. Also the data being sent is very long, and indexes have a limit.)

  • 写回答

1条回答 默认 最新

  • doupao1978 2017-01-11 23:10
    关注

    You can do the test and INSERT in a single query:

    INSERT INTO yourTable (columnName)
    SELECT :data
    FROM DUAL
    WHERE NOT EXISTS (SELECT 1 FROM yourTable WHERE columnName = :data)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集