replace distinct clause by safer subqueries