title: MySQL Using ON DUPLICATE KEY UPDATE in multithreading
body: <p>I'm trying to figure out how to run a SQL query that does:</p>
  
  <pre><code>if(duplicate key):
      UPDATE with VALUES
  else:
      INSERT with VALUES
  </code></pre>
  
  <p>in multiple threads. </p>
  
  <p>Ordinarily I would do a <code>INSERT...ON DUPLICATE KEY UPDATE</code> to accomplish this task, and I would use a <code>SELECT...FOR UPDATE</code> to do the multithreading. But, how can I accomplish both?</p>
  
  <p>Here's my SQL statement without the SELECT...FOR UPDATE</p>
  
  <pre><code>insert into PUSH_MESSAGES (stageOne, stageTwo, stageThree, stageFour, stageFive,
        highestStage, iOSTotal, androidTotal, iOSRunningCount, androidRunningCount, vendorId,
        problem, iOSComplete, totalStageFours, totalStageThrees,
        expectedTotals, startTime, androidComplete, date, topics, androidFailures, iOSFailures,
        latestUpdate)
  
        VALUES($first, $second, $third, $fourth, $fifth, $highestStage, $iOSTotal, $androidTotal,
      $iOSRunningCount, $androidRunningCount, $vendorId, $newProblem, $iOSCompleted, $totalStageFours,
      $totalStageThrees, $expectedTotals, $startTime,$newAndroidComplete, $date, $topics, $androidFailures, $iOSFailures)
  
        ON DUPLICATE KEY UPDATE stageOne=VALUES(stageOne), stageTwo=VALUES(stageTwo), stageThree=VALUES(stageThree),
        stageFour=VALUES(stageFour), stageFive=VALUES(stageFive), highestStage=VALUES(highestStage), iOSTotal=VALUES(iOSTotal),
        androidTotal=VALUES(androidTotal), iOSRunningCount=VALUES(iOSRunningCount), androidRunningCount=VALUES(androidRunningCount),
        vendorId=VALUES(vendorId), problem=VALUES(problem), iOSComplete=VALUES(iOSComplete), androidComplete=VALUES(androidComplete),
        totalStageThrees=VALUES(totalStageThrees), totalStageFours=VALUES(totalStageFours), expectedTotals=VALUES(expectedTotals),
        startTime=VALUES(startTime), date=VALUES(date), topics=VALUES(topics), androidFailures=VALUES(androidFailures),
        iOSFailures=VALUES(iOSFailures)
  </code></pre>
  
  <p>But, when I try and add in the <code>SELECT...FOR UPDATE</code> I end up getting stuck. I figure I must do something like:</p>
  
  <pre><code>select * from push_messages where vendorId=$vendorId for update
  
  update push_messages set...
  </code></pre>
  
  <p>And then I don't know how to put an <code>insert</code> in there? What am I setting in the initial update? Thanks.</p>