Using MySQL, I've got a set of tables with 1->N relationships from member -> items -> photos.
I'm trying to select a list of a member's items + some columns from the first associated photo (by first I mean the photo with the lowest sort order).
Currently I have this query which works, but seems overly complex. Is there an easier way and/or how could this query be improved. In particular, I'm concerned about the inner most select statement - will MySQL optimize this down to only work with photos for the member in question and should I be using additional where clauses in there to help optimize it.
SELECT items.member_id, items.item_id, items.title, p.photo_id, p.blob_id, p.image_width, p.image_height
FROM items
LEFT JOIN
(
SELECT photos.item_id, photos.photo_id, photos.blob_id, photos.image_width, photos.image_height
FROM
(
SELECT item_id, min(sort_order) as min_sort_order
FROM photos
GROUP BY item_id
) AS x
INNER JOIN photos on photos.item_id=x.item_id and photos.sort_order=x.min_sort_order
) AS p ON items.item_id = p.item_id
WHERE items.member_id=1
ORDER BY items.title;