MDL-40230: BACKPORT Remove DISTINCT to avoid using temporary table