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.
Merge pull request #10303 from ahorner/3-2-stable

Preserve context for joins while merging relations