optimize group by primary keys queries