title: Insert/Update into Table with results of another query
body: <p>In my application, I have two tables:  One for tracking records, and another where I'm tracking individual pageviews on certain pages.  Each page view event triggers a record to be written to my Views table.  </p>
  
  <p>In order to calculate stats, I've got a cron job where I'm trying to aggregate the count of these views, grouped by record_id and save them into a separate table. </p>
  
  <p>If I run the following insert query, it works great.</p>
  
  <pre><code>insert into Details (record_id, views)
  (select record_id, count(id) from Views where 1 group by record_id)
  </code></pre>
  
  <p>Unfortunately, this only works for Inserting, and I'm having a hard time coming up with a proper query to Insert/Update.  I've tried using <code>On Duplicate Key Update</code>, but I can't seem to figure out how to get it working with my existing query.  I'm hoping to avoid the alternative, wihch is scripting this in PHP and running a bunch of individual queries, if possible.</p>
  
  <p>Here are my table definitions:</p>
  
  <pre><code>Views
  id (int) PK
  record_id (int)
  created_at (date)
  
  Details
  record_id (int) PK
  views (int)
  </code></pre>
  
  <p><strong>Note:</strong> Also, in the future, I'm planning on adding more columns to the Details table to represent other statistics, so running a Truncate and re-running the original insert query above isn't really a viable solution.</p>