Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are subqueries cached by MySQL when used in a WHERE clause?

In the following query:

SELECT column_a, column_b FROM table_a WHERE
    column_b IN (SELECT b_id FROM table_b)

Is the subquery SELECT b_id FROM table_b cached by the SQL parser, or would it be faster to do the query beforehand, save it as a variable (in PHP, for example), and then pass those values in as a CSV string?

e.g.

SELECT column_a, column_b FROM table_a WHERE
    column_b IN (1,3,4,6,8,10,16,18)
like image 609
Julian H. Lam Avatar asked Aug 08 '12 15:08

Julian H. Lam


1 Answers

Look into using EXPLAIN EXTENDED to fully illustrate the effects dealt on the subquery.

For instance:

EXPLAIN EXTENDED
SELECT column_a, column_b FROM table_a WHERE
    column_b IN (SELECT b_id FROM table_b)

If they do not yield the caching results you wish, you may be interested in storing them either in memory (memcache, redis), on file (using PHP file libraries) or in a separate SQL cache itself.

like image 194
Daniel Li Avatar answered Sep 28 '22 07:09

Daniel Li