SELECT DISTINT service_ID from ..... Fetch into array and loop... foreach (serviceID) { SELECT stop_reference, distance from XXX WHERE service_ID = :p1 AND distance = (SELECT min(distance) from XXX where service_id = :p1) }