title: SQL Conditional INSERT
body: <p>I'm using MySQL.  How can I execute an INSERT into a table predicated upon validation of related data?  Forgive the contrived example.</p>
  
  <p>If my tables are:</p>
  
  <pre><code>&gt; SELECT * FROM colors;
  id color  owner
  -- ------ -----
  10 red    2
  11 banana 6
  12 blue   9
  </code></pre>
  
  <p>and</p>
  
  <pre><code>&gt; SELECT * FROM fruit;
  id  color_id  name
  --  --------  -------
  59  10        cherry
  60  12        blueberry
  </code></pre>
  
  <p>Where fruit.color is a foreign key to colors.id</p>
  
  <p>I want to insert info about a banana, but only if the owner of the color is 6.  Here's the raw INSERT:</p>
  
  <pre><code>INSERT INTO
      fruit
      (color_id, name)
  VALUES
      (11, 'banana');
  </code></pre>
  
  <p>I'd like to do something like:</p>
  
  <pre><code>INSERT INTO
      fruit
      (color_id, name)
  VALUES
      (11, 'banana')
  
  -- ??? I have no idea what to put here ???
  ONLY IF (
      (SELECT COUNT(*) FROM fruit
      INNER JOIN colors ON fruit.color_id = colors.id
      AND   colors.id     = 11
      WHERE colors.owners = 6) &gt;= 1
  )
  </code></pre>
  
  <p>That last clause is obviously not real, but I don't know what to do there.  The idea is only INSERT the values if the <code>owner</code> column of the <code>color_id</code> I'm trying to insert is equal to the value I provide.</p>
  
  <p>Help?</p>