title: Conditional ON DUPLICATE KEY UPDATE (Update only if certain condition is true)
body: <p>I have the following query being used:</p>
  
  <pre><code>INSERT INTO userlist (username, lastupdate, programruncount, ip)
  VALUES (:username, NOW(), 1, :ip)
  ON DUPLICATE KEY UPDATE
  lastupdate = NOW(), programruncount = programruncount + 1, ip = :ip;
  </code></pre>
  
  <p>However, I also want to make the <code>ON DUPLICATE KEY UPDATE</code> conditional, so it will do the following:</p>
  
  <ul>
  <li><strong>IF</strong> <code>lastupdate</code> was less than 20 minutes ago (<code>lastupdate &gt; NOW() - INTERVAL 20 MINUTE</code>).</li>
  <li><strong>True:</strong> Update <code>lastupdate = NOW()</code>, add one to <code>programruncount</code> and then update <code>ip = :ip</code>.</li>
  <li><strong>False:</strong> All fields should be left the same.</li>
  </ul>
  
  <p>I am not really sure how I would do this but after looking around, I tried using an <code>IF</code> Statement in the <code>ON DUPLICATE KEY UPDATE</code> part. </p>
  
  <pre><code>INSERT INTO userlist (username, lastupdate, programruncount, ip)
  VALUES ("testuser", NOW(), "1", "127.0.0.1")
  ON DUPLICATE KEY UPDATE
  IF(lastupdate &gt; NOW() - INTERVAL 20 MINUTE, VALUES(lastupdate, programruncount + 1),
  lastupdate, programruncount);
  </code></pre>
  
  <p>However I am getting the following error: <code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF(lastupdate &gt; NOW() - INTERVAL 20 MINUTE, VALUES(lastupdate, programruncount +' at line 6</code></p>