title: how to optimize sql query with indexes
body: <p>I have this complicated query and I need to optimize that.
  Without indexes it takes 20ms, I'tried add some indexes, its better, now I have 4ms.
  But I dont have any experience. Can you help me to make it even faster?</p>
  
  <pre><code> SELECT COUNT(*) FROM(
     SELECT user_id FROM times 
        INNER JOIN tags ON times.user_id = tags.tag_id 
        INNER JOIN users ON tags.user_nr = users.nr  
        WHERE (times.time &lt; 1597313) 
          AND (times.run_id="118") 
          AND (times.user_id != 109330258) 
          AND (times.user_id != 0) 
          AND (times.time != 0 ) 
          AND (times.cell != 1 ) 
          AND (users.category_id="4") 
          GROUP BY user_id HAVING count(*) == 1 
     UNION  
     SELECT user_id FROM times 
     INNER JOIN tags ON times.user_id = tags.tag_id 
     INNER JOIN users ON tags.user_nr = users.nr  
     WHERE (times.run_id="118") 
       AND (times.user_id != 109330258) 
       AND (times.user_id != 0 ) 
       AND (times.time != 0 ) AND (times.cell != 1 ) 
       AND (users.category_id="4") 
       GROUP BY user_id HAVING count(*) &gt; 1
     )
  </code></pre>
  
  <p>I added 3 indexes.</p>
  
  <ul>
  <li>table tags - tagid </li>
  <li>table times - user_id </li>
  <li>table user - nr</li>
  </ul>