Refactor join query logic.