Fix issue with nested reference queries not being prepared properly.