tags:

views:

44

answers:

1

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;
A: 
SELECT 
        items.member_id, items.item_id, items.title, photo.photo_id, photo.blob_id, photo.image_width, photo.image_height
FROM 
        items
JOIN photos on items.item_id = photos.item_id
JOIN (SELECT item_id, min(sort_order) as min_sort_order
        FROM photos
        GROUP BY item_id) min_photo on photos.item_id=min_photo.item_id and photos.sort_order=min_photo.min_sort_order
WHERE items.member_id=1
ORDER BY items.title;
Parkyprg
Almost. I forgot to mention that items don't have to have a photo. This query doesn't return those items.
cantabilesoftware
In that case, your query seems to be ok.
Parkyprg