title: MySQL - how can this query be optimized?
body: <p>I am trying to generate a list of all user's tags with a count of the number of tasks they are associated with...</p>
  
  <pre><code>SELECT * FROM 
   ( SELECT tags.tag_id, tags.tag_text, tags.type, task_tags.tag_id AS task_tag_id,
     count(task_tags.tag_id) AS TaskCount 
     FROM tags 
     LEFT JOIN task_tags ON tags.tag_id = task_tags.tag_id 
     WHERE tags.user_id = 2 
     GROUP BY tag_id ) 
  AS temp_table ORDER BY tag_text
  </code></pre>
  
  <p>Here are the EXPLAIN results:</p>
  
  <pre><code>id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra   
  1   PRIMARY     &lt;derived2&gt;  ALL     NULL    NULL    NULL    NULL    13  Using filesort
  2   DERIVED     tags    ref     user_tag    user_tag    4   const   13  Using where; Using temporary; Using filesort
  2   DERIVED     task_tags   ref     tag_id  tag_id  4   taskmandb1234.tags.tag_id   1   Using index
  </code></pre>