Fix pagination when using distinct() in query