我需要从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
第一个返回的记录。
答案 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