title: Add row if not exists, or retrieve its id for other query
body: <p>This questions mixes several questions already answered, but I can't put all the answers together to make it work.</p>
  
  <p>I have three tables :</p>
  
  <p>Table <strong><code>users</code></strong> :</p>
  
  <p><code>| user_id | user_name |</code></p>
  
  <p>Table <strong><code>events</code></strong> :</p>
  
  <p><code>| event_id | event_date | event_name |</code></p>
  
  <p>Table <strong><code>user_event</code></strong> :</p>
  
  <p><code>| user_id | event_id |</code></p>
  
  <p>Table <strong><code>user_event</code></strong> is a child from the previous tables and associate a user to an event (foreign keys defined to its parent table, with <code>ON DELETE CASCADE</code>).</p>
  
  <p>Each user can add an event, but if the event already exists, it won't create a duplicate in the table <strong><code>events</code></strong>, but will still insert a row in <strong><code>user_event</code></strong> with the <code>user_id</code> and the <strong>existing</strong> <code>event_id</code> of the event already saved.</p>
  
  <p>The code I have to only add an event if it doesn't exist already :</p>
  
  <pre><code>INSERT INTO `events` (`event_id`, `event_date`, `event_name`) 
  SELECT * FROM (SELECT 'event_1', '2014-05-20',  'Meeting') AS tmp 
  WHERE NOT EXISTS (
      SELECT `event_id`, `event_date`, `event_name` 
      FROM `events` 
      WHERE `event_name` = 'Meeting' 
      AND `event_date` = '2014-05-20') 
  LIMIT 1;
  </code></pre>
  
  <p>Then I want to save it into user_event table so that I know that this user is going to this event :</p>
  
  <pre><code>INSERT INTO `user_event` (`user_id`, `event_id`) VALUES ('user_1', 'event_1');
  </code></pre>
  
  <p>If it is a new event, it is all fine as I know the event ID in advance but if another user is creating an already existing event :</p>
  
  <p><code>user_2</code> creates the following event (same as previously inserted, but different id) :</p>
  
  <pre><code>`event_name` = 'Meeting'
  `event_date` = '2014-05-20'
  `event_id` = 'event_2'
  </code></pre>
  
  <p>I want to insert in the table <code>user_event</code> the following entry :</p>
  
  <pre><code>| user_2 | event_1 |
  </code></pre>
  
  <p>Maybe it is possible to combine those queries into one and user sql variables, or maybe by defining <code>id = last_insert_id(id)</code> and retrieving it through php before submitting the second query, but can't make it work.</p>