I have a database that stores "themes" and every theme is associated with a whole bunch of images (=screenshots of these themes). Now I want to display the latest 10 themes and for every theme I only want to get one single image from the database (the one with the lowest ID).
Currently my query looks like this (I am using a subquery):
SELECT DISTINCT
t.theme_id, t.theme_name, theme_date_last_modification, image_id, image_type
FROM
themes t, theme_images i
WHERE
i.theme_id = t.theme_id
AND t.theme_status = 3
AND t.theme_date_added < now( )
AND i.image_id = (
SELECT MIN( image_id )
FROM theme_images ii
WHERE ii.theme_id = t.theme_id
)
GROUP BY
t.theme_id
ORDER BY
t.theme_date_last_modification DESC
LIMIT 10
It works, but the query is very slow. When I use EXPLAIN I can see that there's a "dependent subquery". Is it possible to convert this dependent subquery into some kind of join that can be processed faster by mysql?
P.S.: My actual query is much more complex and makes use of more tables. I have already tried to simplify it as much as possible so that you can concentrate on the actual reason for the performance-problems.
EDIT: This is the output of EXPLAIN:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY t index PRIMARY,themes themes 212 NULL 5846 Using where; Using index; Using temporary; Using filesort
1 PRIMARY i eq_ref PRIMARY,theme_id,image_id PRIMARY 4 func 1 Using where
2 DEPENDENT SUBQUERY ii ref theme_id theme_id 4 themes.t.theme_id 6