item_tag_map has two column item_id and tag_id and both of them have index.
Here's a data sample:
item_id tag_id
1 1
1 3
4 7
1 5
3 1
3 8
6 8
10 4
Now I want to obtain item ids which have tags 1,2,3,5 and sort the result by the total count of all tags.
Here's a result sample:
item_id count(m.tag_id)
1 3
3 1
The SQL I tried was:
SELECT m.item_id,count(m.tag_id) from item_tag_map AS m
WHERE tag_id in(1,2,3,5)
GROUP BY m.item_id
ORDER BY count(m.tag_id)
LIMIT 10
There're about 10k rows in this table and the query was very slow. I tried to remove all count statement, then it became very fast than before.
Why would count slow down this query? How to optimize this query to make it fast?
countin select count(m.tag_id) from ... slows down it.And here's the explain result:id:1;select_type:simple;table:m;type:index;possible_keys:tag_id;key:item_id;key_len:4;ref:null;extra:using where using temporary using filesortUSE INDEX(tag_id)to force it usingtag_idbut notitem_idas index, it became a lot more faster than before which still costed 2s to finish the query.