title: MySQL Insert row, on duplicate: add suffix and re-insert
body: <p>My question is rather complex, but I thought I should give it a try.</p>
  
  <p>In short, I want to insert a row with a <code>slug</code> (short string with alphas and a dash: this-is-a-slug). The problem is that <code>slug</code> is a unique key and there might be duplicates.</p>
  
  <p>When there is a duplicate it should be inserted with a modified <code>slug</code>, like with a suffix: this-is-a-slug-1, if that fails increase the suffix: this-is-a-slug-2.</p>
  
  <p>Here's the tricky part, it should be accomplished in MySQL (no PHP involved) and preferably in a INSERT statement (no variables, procedures etc.)</p>
  
  <p>I've tried a simple solution like so:</p>
  
  <pre><code>INSERT INTO table (slug) VALUES(IF((SELECT COUNT(slug) FROM table WHERE slug = 'this-is-a-slug') &gt; 0, 'this-is-a-slug-1', 'this-is-a-slug');
  </code></pre>
  
  <p>This should insert <code>this-is-a-slug-1</code> if <code>this-is-a-slug</code> exists, or <code>this-is-a-slug</code> otherwise.</p>
  
  <p>Expectedly, however, this spawns an error telling me that I cannot you a <code>FROM</code> statement in an <code>UPDATE</code> statement, or something like that.</p>
  
  <p>That's the problem, hope anyone can say something about it.</p>
  
  <p>P.S.: This is being used in a really heave RSS news update procedure, in which I can easily check the slug in the db with php and then modify it, but that doubles the time of my script :|, so I thought I could make it hard for mysql rather than php.</p>