はじめに
MySQLを5.7にアップデートしたときにgroup byを使用しているコードでエラーが発生したので、その対応をまとめます。
問題
エラー文
select id, company_id from users group by company_id;
SELECT list is not in GROUP BY clause and contains nonaggregated column 'users.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
原因は、GROUP BYで指定されていないカラムを、SELECTで指定することによるエラーです。
MySQL5.6までは、ONLY_FULL_GROUP_BYという設定が無効でしたが、MySQL5.7からこの設定がデフォルトで有効になっているためエラーが出るようになります。
解決方法
ANY_VALUEを使用する
ANY_VALUE関数を使用することで、GROUP BYで指定されていないカラムを、SELECTで指定することができるようになります。
select any_value(id), company_id from users group by company_id;
設定を変更する
ONLY_FULL_GROUP_BYの設定を無効にして、エラーが出ないようにします。
参考