Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unfortunately, MySQL is not very good at optimizing subqueries with IN. This is from <a href="http://dev.mysql.com/doc/refman/5.5/en/subquery-restrictions.html" rel="nofollow">MySQL documentation</a>:</p> <blockquote> <p>Subquery optimization for IN is not as effective as for the = operator or for the IN(value_list) operator.</p> <p>A typical case for poor IN subquery performance is when the subquery returns a small number of rows but the outer query returns a large number of rows to be compared to the subquery result.</p> <p>The problem is that, for a statement that uses an IN subquery, the optimizer rewrites it as a correlated subquery. Consider the following statement that uses an uncorrelated subquery:</p> <p>SELECT ... FROM t1 WHERE t1.a IN (SELECT b FROM t2);</p> <p>The optimizer rewrites the statement to a correlated subquery:</p> <p>SELECT ... FROM t1 WHERE EXISTS (SELECT 1 FROM t2 WHERE t2.b = t1.a);</p> <p>If the inner and outer queries return M and N rows, respectively, the execution time becomes on the order of O(M×N), rather than O(M+N) as it would be for an uncorrelated subquery.</p> <p>An implication is that an IN subquery can be much slower than a query written using an IN(value_list) operator that lists the same values that the subquery would return.</p> </blockquote> <p>Try using a JOIN instead.</p> <p>Because MySQL works from the inside out, sometimes you can trick MySQL by wrapping the subquery inside yet another subquery like so:</p> <pre><code>SELECT COUNT(*) FROM table_name WHERE device_id IN (SELECT * FROM (SELECT DISTINCT device_id FROM table_name WHERE NAME = 'SOME_PARA') tmp) </code></pre> <p>Here's the JOIN solution:</p> <pre><code>SELECT COUNT(DISTINCT t2.id) FROM table_name t1 JOIN table_name t2 ON t2.device_id = t1.device_id WHERE t1.NAME = 'SOME_PARA' </code></pre> <p>Notice that I start from the inside and go out also.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload