currently im working with mysql 5.7 in development, and 5.6 in production. Each time i run a query with a group by in development i get some error like "Error Code: 1055. Expression #1 of SELECT list is not in GROUP BY "
Here is the query.
SELECT c.id, c.name, i.*
FROM countries c, images i
WHERE i.country_id = c.id
GROUP BY c.id; Fixed for 5.7;
SELECT c.id, c.name,
ANY_VALUE(i.url) url,
ANY_VALUE(i.lat) lat,
ANY_VALUE(i.lng) lng
FROM countries c, images i
WHERE i.country_id = c.id
GROUP BY c.id;
For solving that I use the mysql function from 5.7 ANY_VALUE, but the main issue is that its not available in mysql 5.6
So if I fix the sql statement for development i will get an error in production.
Do you know any solution or polifill for the ANY_VALUE function in mysql 5.6?
For decades you could write queries that were not valid in standard SQL but perfectly valid mysql
This comes from the Mysql 5.6 manual's page on GROUP BY. If you look at the same page for 5.7.6 you see that things have changed. And changed dramatically!!
That page also gives you the solution. Disable
ONLY_FULL_GROUP_BY
That will make it possible for your old 5.6 query to work on 5.7.6 (remove ANY_VALUE from your query since it's not available in 5.7.6 but use the ONLY_FULL_GROUP_BY instead).Instead of
ANY_VALUE
, you could use theMIN
orMAX
aggregate functions.Alternatively, you might consider not setting the
ONLY_FULL_GROUP_BY
SQL mode, which is set by default for MySql 5.7, and is responsible for the difference you experience with MySql 5.6. Then you can delay the update of your queries until you have migrated all your environments to MySql 5.7.Which of the two is the better option, is debatable, but in the long term it will be better to adapt your queries so they adhere to the
ONLY_FULL_GROUP_BY
rule. UsingMIN
orMAX
can certainly be of use in doing that.You're misusing the notorious nonstandard MySQL extension to GROUP BY. Standard SQL will always reject your query, because you're mentioning columns that aren't aggregates and aren't mentioned in
GROUP BY
. In your dev system you're trying to work around that withANY_VALUE()
.In production, you can turn off the ONLY_FULL_GROUP_BY MySQL Mode. Try doing this:
This will allow MySQL to accept your query.
But look, your query isn't really correct. When you can persuade it to run, it returns a randomly chosen row from the
images
table. That sort of indeterminacy often causes confusion for users and your tech support crew.Why not make the query better, so it chooses a particular image. If your
images
table has an autoincrementid
column you can do this to select the "first" image.That will return one row per country with a predictable image shown.