Note that there are some explanatory texts on larger screens.

plurals
  1. POImprove MySQL Query with IN Subquery
    primarykey
    data
    text
    <p>I hava a table <code>items</code> and a table <code>item_attributes</code>.</p> <p>For simplicity let's say my table item has a column <code>id</code> and a column <code>name</code>. Of cource there is a index on the <code>id</code> column.</p> <p>the <code>item_attributes</code> table has the columns <code>id</code>, <code>item_id</code>, <code>attribute_name</code> and <code>attribute_value</code> and an index ON <code>attrubute_name</code></p> <p>Now I want to query all items with a specific attribut without using a join.</p> <p>I do this with the following query:</p> <pre><code>SELECT * FROM items i WHERE i.id IN ( SELECT item_id FROM item_attributes a WHERE a.attribute_name = 'SomeAttribute' AND a.attribute_value = 'SomeValue' ) </code></pre> <p>the SubQuery itself runs fast.</p> <p>If I execute the query itself first and use the result for an IN query</p> <pre><code>SELECT * FROM items i WHERE i.id IN (1,3,5,7,10,...) </code></pre> <p>it is fast, too.</p> <p>However, combined the query is very, very slow (>2 secs.) If I investigate the query plan I see why: MySQL does a full table scan on the items table instead of executing the subquery first and using the result for an index query.</p> <pre><code>1, 'PRIMARY', 'items', 'ALL', '', '', '', '', 149726, 'Using where' 2, 'DEPENDENT SUBQUERY', 'item_attributes', 'index_subquery', 'IDX_ATTRIBUTE_NAME', 'IDX_ATTRIBUTE_NAME', '4', 'func', 1, 'Using where' </code></pre> <p>Is there a way to optimize this query? I know that the subquery will always return only a small resultset (&lt;100 rows).</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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