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