prevent qrewrite returning same nested query as the main one

* this was happening if querying by PK, and the field [that was in keylearning] is not available in results
* minor refactoring
Merge pull request #4160 from dmwm/query_rewrite_fix

prevent qrewrite returning same nested query as the main one