title: How to upsert two database tables with one SQL statement?
body: <p>There are two database tables described in the following. The asterisk highlights the primary keys.</p>
  
  <pre><code>+----------------+    +----------------+
  | posts          |    | url_references |
  +----------------+    +----------------+
  | id*            |    | url*           |
  | post_content   |    | post_id        |
  +----------------+    +----------------+
  </code></pre>
  
  <p>I want to <strong><em>insert</em> or <em>update</em> a <em>post</em></strong> based on the existence of the corresponding entry in the table <em>url_references</em>. What is the best <strong>combination of SQL commands</strong> to reach this? I would like to <strong>avoid</strong> to process the decision about <em>insert</em> or <em>update</em> in <strong>PHP</strong>.<br>
  The following scenarios describe the alternative step by step behavior using PHP commands.</p>
  
  <pre><code>SELECT * FROM url_references WHERE url = $url;
  </code></pre>
  
  <p>Scenario 1: Insert new entry.</p>
  
  <pre><code>// mysql_num_rows() returns 0
  INSERT INTO post (post_content) VALUES ($postContent);
  $postId = mysql_insert_id();
  INSERT INTO url_references (url, post_id) VALUES ($url, $postId);
  </code></pre>
  
  <p>Scenario 2: Update existing entry.</p>
  
  <pre><code>// mysql_num_rows() returns 1
  $row = mysql_fetch_array($rows);
  $postId = $row['post_id'];
  UPDATE posts SET post_content = $postContent WHERE id = post_id;
  </code></pre>
  
  <hr>
  
  <p><strong>Edit 1:</strong> Note, that I cannot check for the <em>id</em> in <em>posts</em> directly! I want to manage (insert/update) <em>posts</em> based on their <em>url</em> as the primary key.</p>