从内部联接中检索不同的记录

时间:2013-01-12 00:34:34

标签: mysql sql greatest-n-per-group

我需要从portfolio_images检索第一张图片,而我的后续查询却没有这样做。当我只需要它找到的第一个portfolio记录时,它会返回找到的每个portfolio_images.fullsize记录的所有图像(这适用于DISTINCT)。

组合

id | project_name | location_id | project_type | is_active

portfolio_images

id | portfolio_id | fullsize

 SELECT DISTINCT p.project_name, pi.fullsize
    FROM portfolio p
    INNER JOIN portfolio_images pi ON p.id = pi.portfolio_id
    AND p.is_active = 1
    AND p.project_type = 'project' AND p.location_id = 3
    ORDER BY p.oindex

我想避免首先查询portfolio,然后循环遍历这些结果并执行嵌套循环,根据当前投资组合ID查询portfolio_images第一个返回的记录。

1 个答案:

答案 0 :(得分:2)

添加一个子查询,该子查询获取表portfolio_id上每个portfolio_images的最后一个ID。这将确保您为每个project_name获得一条记录。

SELECT  p.project_name, pi.fullsize
FROM    portfolio p
        INNER JOIN portfolio_images pi 
            ON p.id = pi.portfolio_id AND 
                p.is_active = 1 AND 
                p.project_type = 'project' AND 
                p.location_id = 3
        INNER JOIN
        (
            SELECT  portfolio_id, MAX(ID) max_ID
            FROM    portfolio_images 
            GROUP BY portfolio_id
        ) a ON pi.portfolio_id = a.portfolio_id AND
                pi.ID = a.max_ID
ORDER   BY p.oindex