开发者

SQL - selecting first matching record for join

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 partic开发者_C百科ular, 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;


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜