title: MySQL query is too slow, how can I improve this?
body: <p>I have this query, that on a table with ~300.000 rows take about 14sec to extract data.
  This table will increase its size in the near future...over a million rows.
  I have used the <code>EXISTS</code> clause instead of the <code>IN</code> clause, and I give an improvement.
  But the query is too slow.
  Can you have any solution?
  Thanks in advance.</p>
  
  <p>This is the query:</p>
  
  <pre><code>SELECT 
      flow,
      COUNT(*) tot
  FROM
      (
          SELECT 
              ff.session_id,
              GROUP_CONCAT(ff.page, '#', ff.snippet_params,'$',ff.is_lead SEPARATOR '|') flow 
              FROM table_a ff
              WHERE EXISTS 
                  (
                      SELECT
                          f.session_id
                      FROM table_a f
                      WHERE f.session_id = ff.session_id
                      AND f.is_lead = 1
                      GROUP BY f.user_id 
                      ORDER BY f.user_id, f.`timestamp` 
                  )
              GROUP BY ff.user_id 
              ORDER BY ff.user_id, ff.`timestamp`, ff.session_id 
      )
  AS flow
  GROUP BY flow 
  ORDER BY tot DESC LIMIT 10
  </code></pre>
  
  <p>This is the explain:</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)                            532  Using temporary; Using filesort               
   2  DERIVED             ff          ALL     (NULL)              (NULL)      (NULL)   (NULL)                         322154  Using temporary; Using filesort               
   3  DEPENDENT SUBQUERY  f           ref     is_lead,session_id  session_id  767      ff.session_id       3  Using where; Using temporary; Using filesort  
  </code></pre>