Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>MySQL is really bad at optimizing subqueries like this, so you have to help it bit, if possible, rewriting it using joins. For the first subquery this should be easy:</p> <pre><code>SELECT SUM( quantity * weight /1000 ) FROM `inventory_transactions` it JOIN (SELECT product_nr, IF( netoweight = '', weight, netoweight ) AS weight FROM products) AS products ON product.product_nr = it.item WHERE it.type = 'Production' AND it.item &gt; '200000' AND it.item &lt; '400000' AND it.date LIKE '2013-01%' AND ( ( SELECT COUNT( id ) FROM structure WHERE final_item = it.item AND level &gt; '1' ) &lt;1 ) </code></pre> <p>However, this will likely not yet solve the problem with not using keys on the product table, since the second query is more complicated. However, it should be rewritable using group by:</p> <pre><code>SELECT SUM( quantity * weight /1000 ) FROM `inventory_transactions` it JOIN (SELECT product_nr, IF( netoweight = '', weight, netoweight ) AS weight FROM products) AS products, ON product.product_nr = it.item LEFT OUTER JOIN (SELECT final_item, COUNT( id ) AS count FROM structure WHERE level &gt; '1' GROUP BY final_item) AS struct_count ON it.item = struct_count.final_item WHERE it.type = 'Production' AND it.item &gt; '200000' AND it.item &lt; '400000' AND it.date LIKE '2013-01%' AND struct_count.count IS NULL </code></pre> <p>The <code>IS NULL</code> part is needed for products with structure count 0, since they will not match in the join. This query should be much easier for the query processor to use appropriate indexes. If it still won't use them, check you have them on the correct columns.</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.
 

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