3 million rows entries are in table A, so when we explain this query it give us this result
±—±------------±--------------------±------±----------------------------------------------------±-------------±--------±-----±--------±----------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
±—±------------±--------------------±------±----------------------------------------------------±-------------±--------±-----±--------±----------------------------------------------------------+
| 1 | SIMPLE | A | range | value1_3 | value1_3 | 8 | NULL | 3124145 | Using where; Using index; Using temporary; Using filesort |
±—±------------±--------------------±------±----------------------------------------------------±-------------±--------±-----±--------±----------------------------------------------------------+
select gallery_id,image_position,count(gallery_id) as ct from gallery_event_image WHERE image_position < 255 and gallery_id!=0 and gallery_id != ‘’ group by gallery_id,image_position having ct >1 order by ct asc limit 500;
if you want the lowest 500 counts, you’re going to have to compute all the counts, right?
that’s what using temporary and using filesort mean – each gallery_id/image_position combination is counted, the results are placed into a temporary file, and then this file is sorted into ascending sequence by the count
that’s what you asked for, and your query is as optimized as it’s going to get