replaced distinct by more efficient subquery