SELECT COUNT(*)
FROM song AS s
JOIN user AS u
ON(u.user_id = s.user_id)
WHERE s.is_active = 1 AND s.public = 1
The s.active and s.public are index as well as u.user_id and s.user_id.
song table row count 310k
user table row count 22k
Is there a way to optimize this? We’re getting 1 second query times on this.
Ensure that you have a compound “covering” index on song:
(user_id, is_active, public). Here, we’ve named the indexcovering_index:Here, we’re ensuring that the JOIN is done with the covering index instead of the primary key, so that the covering index can be used for the WHERE clause as well.
I also changed
COUNT(*)toCOUNT(s.user_id). Though MySQL should be smart enough to pick the column from the index, I explicitly named the column just in case.Ensure that you have enough memory configured on the server so that all of your indexes can stay in memory.
If you’re still having issues, please post the results of
EXPLAIN.