Select full record with minimum value for column grouped by joined value
you are missing on {condition} for your last join :
however I'm not sure
select images.*, unit_id 
from images 
join images_units 
    on images.id = images_units.image_id 
join images_sites 
    on images.id = images_sites.image_id 
join (
    select min(sort) as minSort, unit_id as matchID 
    from images 
    join images_units 
        on images.id=images_units.image_id 
    group by matchID
    ) as sq 
    on sq.matchId = ??  -- &lt;-- here add the proper join condition
where 
images.sort = minSort 
and a.unit_id = matchID 
and site_id = xyz;