Improved join query generation