title: MySQL - Selecting row with two columns match from a table. If doesn't exist select row with one column
body: <p>Table:</p>
  
  <pre><code>country_id           state_id           rate
  200                   100                1.1
  200                   -1                 5.1
  </code></pre>
  
  <p>I'm trying to create a prioritized select using two combinations:
  1. country_id = 200 and state_id = 100. 
  2. If given combination doesn't exist get country_id = 200 and state_id = -1
  Note: the table is not necessarily going to have both rows, they may exist independently. </p>
  
  <p>Tried to use </p>
  
  <pre><code>SELECT CASE a.rate &gt; 0 THEN a.rate ELSE b.rate AS rate
  FROM 
  (
      (SELECT * FROM taxes WHERE country_id = 200 and state_id = 100) AS a,
      (SELECT * FROM taxes WHERE country_id = 200 and state_id = -1) AS b
  )
  </code></pre>
  
  <p>another option I've tried is using UNION as subquery. </p>
  
  <pre><code>SELECT CASE b.a_rate &gt; 0 THEN b.a_rate ELSE b.b_rate AS rate
  FROM 
  (
      (
         SELECT rate AS a_rate FROM taxes WHERE country_id = 200 and state_id = 100
         UNION
         SELECT rate AS b_rate FROM taxes WHERE country_id = 200 and state_id = -1
      ) AS b
  )
  </code></pre>
  
  <p>Both work fine only if you have both rows in the table and fails if one of them is missing... any ideas?</p>