title: MySQL: INSERT or UPDATE if exists, but not based on key column
body: <p>What I have is a table of completed training. Each user has a username. Each user may completed numerous courses.</p>
  
  <p>The table has the following headers:</p>
  
  <pre><code>+-------------------------+----------+---------+---------+---------+---------+-----------+
  | recordnumber (KEY - AI) | username |  type   | course  | status  | started | completed |
  +-------------------------+----------+---------+---------+---------+---------+-----------+
  | int                     | varchar  | varchar | varchar | varchar | date    | date      |
  +-------------------------+----------+---------+---------+---------+---------+-----------+
  </code></pre>
  
  <p>And I have a PHP script set up to populate the db from a CSV upload.</p>
  
  <p>What I'm trying to achieve is for it to add new rows, and to update existing ones.</p>
  
  <p>The problem is that recordnumber (they key, unique field) is not constant. So instead of doing a "ON DUPLICATE KEY" query, I want to do it based on whether username and course already exist as a row.</p>
  
  <p>Basically to say "If this username already has this course, update the other fields. If the username does not have this course, add this as a new row".</p>
  
  <p>The query that I have at the moment (which works based on key) is:</p>
  
  <pre><code>INSERT into table(recordnumber, username,type,course,status,started,completed) values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')
  
  ON DUPLICATE KEY UPDATE username='$data[1]',type='$data[2]',course='$data[3]',status='$data[4]',started='$data[5]',completed='$data[6]'
  </code></pre>
  
  <p>Any thoughts on how I could amend the query to get it to check based on username and course instead of duplicate key?</p>
  
  <p>Thank you. :-)</p>