Preserve context for joins while merging relations

This is a backport of #10164, already merged into
master. The issue is described in lengthy detail
in issues #3002 and #5494.