Mysql join with counting results in another table <p>I have two tables, one with ranges of numbers, second with numbers. I need to select all ranges, which have at least one number with status in (2,0). I have tried number of different joins, some of them took forever to execute, one which I ended with is fast, but it select really small number of ranges.</p> <pre><code> SELECT SQL_CALC_FOUND_ROWS md_number_ranges.* FROM md_number_list JOIN md_number_ranges ON md_number_list.range_id = md_number_ranges.id WHERE md_number_list.phone_num_status NOT IN (2, 0) AND md_number_ranges.reseller_id=1 GROUP BY range_id LIMIT 10 OFFSET 0 </code></pre> <p>What i need is something like "select all ranges, join numbers where number.range_id = range.id and where there is at least one number with phone_number_status not in (2, 0).</p> <p>Any help would be really appreciated.</p> <p>Example data structure:</p> <p>md_number_ranges:</p> <pre><code>id | range_start | range_end | reseller_id 1 | 000001 | 000999 | 1 2 | 100001 | 100999 | 2 </code></pre> <p>md_number_list:</p> <pre><code>id | range_id | number | phone_num_status 1 | 1 | 0000001 | 1 2 | 1 | 0000002 | 2 3 | 2 | 1000012 | 0 4 | 2 | 1000015 | 2 </code></pre> <p>I want to be able select range 1, because it has one number with status 1, but not range 2, because it has two numbers, but with status which i do not want to select.</p>