title: Getting multicolumn qualifiers, INNER JOINs, and UNIONs to work together
body: <p>I'm trying to get a list of IDs from three tables. </p>
  
  <pre><code>table_one
  ---------
  | id | other_data |
  
  table_two
  ---------
  | this_id | user_id | time_qual |
  
  table_three
  ---------
  | this_id | second_qual |
  </code></pre>
  
  <p>I want to get a list back of <code>table_one</code> <code>id</code>s with the following qualifications:</p>
  
  <ol>
  <li>the <code>id</code> is also found in <code>table_three</code>'s <code>this_id</code></li>
  <li><code>second_qual</code> in <code>table_three</code> is equal to 1</li>
  <li><code>this_id</code> in <code>table_two</code> equals <code>table_one</code>'s <code>id</code> AND in the same row, <code>table_two</code>'s <code>user_id</code> equals the php variable <code>$user_id</code> AND <code>time_qual</code> in that row equals 1.</li>
  <li>but also include <code>id</code>s that qualify for #1 and #2, and not #3 if <code>table_one</code>'s <code>id</code> and the php variable <code>$user_id</code> isn't found on the <strong>same row</strong> of <code>table_two</code></li>
  </ol>
  
  <p>This is my attempt:</p>
  
  <pre><code>        SELECT tb1.id FROM table_one tb1
            INNER JOIN table_two tb2
            INNER JOIN table_three tb3
            WHERE tb2.this_id = tb1.id
             AND tb3.this_id = tb1.id
             AND tb3.second_qual = 1
             AND ((tb2.user_id = $user_id AND tb2.time_qual = 1)
                OR ($user_id NOT IN (SELECT user_id FROM table_two)))
             GROUP BY tb1.id
  </code></pre>
  
  <p>I'm guessing there should be a <code>UNION</code> in there and that <code>tb2.this_id = tb1.id</code> eliminates the results I want from #4, but I'm not sure what to do.</p>
  
  <p>Thanks in advance!</p>