Fix and simplify merge query