1

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

文件夹

id | project_name | location_id | project_type | is_active

投资组合图像

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,然后遍历这些结果并执行嵌套循环以portfolio_images根据当前投资组合 ID 查询第一个返回的记录。

4

1 回答 1

2

添加一个子查询,获取portfolio_idtable 上每个的最后一个 ID portfolio_images。这将确保您将为每个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
于 2013-01-12T00:37:41.440 回答