SQL optimisation to remove unnecessary IN queries