I have a legacy application in which Group By
has been used along with non aggregate columns to fetch the first row for each group. The query is as following:
SELECT
columnPrimaryKey,
column1,
column2,
column3
FROM
(SELECT
columnPrimaryKey,
column1,
column2,
column3
FROM testTable
ORDER BY column2
) AS tbl
GROUP BY column3
Recently, the version was updated to 5.7.22 and now the above query is not returning expected results even after disabling the ONLY_FULL_GROUP_BY
mode.
Yes, I can rewrite the query as following to work according to the new behavior as:
SELECT
x.columnPrimaryKey,
x.column1,
x.column2,
x.column3
FROM tableName AS x INNER JOIN (
SELECT
MIN( column2 ) AS column2,
column3
FROM tableName
GROUP BY column3
) AS y ON x.column2 = y.column2 AND x.column3 = y.column3;
Unfortunately, that's not an option for now. The only option I see is to downgrade to 5.7.5 earlier.
Fiddle 5.7 with 'ONLY_FULL_GROUP_BY' disabled and unexpected results:
https://www.db-fiddle.com/f/8VjB7XpkobWVyXpPvUaGt2/0
Fiddle 5.6 with default modes and expected results:
https://www.db-fiddle.com/f/8VjB7XpkobWVyXpPvUaGt2/1
My question is: Is there any way to disable this behavior of random selection so that the legacy code works without rewriting them or downgrading?
Any suggestions greatly appreciated!