I’m looking for a way to optimize one SQL query that I have. I’m trying to get how many poems with a certain genre.
Query looks like this:
SELECT
COUNT(*)
FROM
`poems`
WHERE `id` IN (
SELECT `poem_id`
FROM `poems_genres`
WHERE `genre_title` = 'derision'
)
AND `status` = 'finished';
It takes too long (about 6-10 seconds), because it can’t use indexes (because of IN() I think?). Is there a way to rewrite this query in different way to get the same result faster?
MySQL has a problem with
inwhere it repeatedly re-evaluates uncorrelated sub queries as though they were correlated. Does rewriting as a join improve things?If not then according to this article (see the section “How to force the inner query to execute first”) wrapping it up in a derived table might help.