[4.2] Backport: Add subselect to query builder

This was originally a PR by me towards 4.2, but somehow it only ended up in what is now 5.0.