Note that there are some explanatory texts on larger screens.

plurals
  1. POStrange Performance Issues with INNER JOIN vs. LEFT JOIN
    primarykey
    data
    text
    <p>I was using a query that looked similar to this one:</p> <pre><code>SELECT `episodes`.*, IFNULL(SUM(`views_sum`.`clicks`), 0) as `clicks` FROM `episodes`, `views_sum` WHERE `views_sum`.`index` = "episode" AND `views_sum`.`key` = `episodes`.`id` GROUP BY `episodes`.`id` </code></pre> <p>... which takes ~0.1s to execute. But it's problematic, because some <code>episodes</code> don't have a corresponding <code>views_sum</code> row, so those episodes aren't included in the result.</p> <p>What I want is NULL values when a corresponding <code>views_sum</code> row doesn't exist, so I tried using a LEFT JOIN instead:</p> <pre><code>SELECT `episodes`.*, IFNULL(SUM(`views_sum`.`clicks`), 0) as `clicks` FROM `episodes` LEFT JOIN `views_sum` ON (`views_sum`.`index` = "episode" AND `views_sum`.`key` = `episodes`.`id`) GROUP BY `episodes`.`id` </code></pre> <p>This query produces the same columns, and it also includes the few rows missing from the 1st query.</p> <p><em>BUT</em>, the 2nd query takes 10 times as long! A full second.</p> <p>Why is there such a huge discrepancy between the execution times when the result is so similar? There's nowhere <em>near</em> 10 times as many rows — it's like 60 from the 1st query, and 70 from the 2nd. That's not to mention that the 10 additional rows have no <code>views</code> to sum!</p> <p>Any light shed would be greatly appreciated!</p> <p>(There are indexes on <code>episodes.id</code>, <code>views_sum.index</code>, and <code>views_sum.key</code>.)</p> <p><strong>EDIT:</strong></p> <p>I copy-pasted the SQL from above, and here are the EXPLAINs, in order:</p> <pre><code>id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE views_sum ref index,key index 27 const 6532 Using where; Using temporary; Using filesort 1 SIMPLE episodes eq_ref PRIMARY PRIMARY 4 db102914_itw.views_sum.key 1 Using where id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE episodes ALL NULL NULL NULL NULL 70 Using temporary; Using filesort 1 SIMPLE views_sum ref index,key index 27 const 6532 </code></pre>
    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.
 

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