0
0

【MySQL】 SELECT list is not in GROUP BY clause and contains nonaggregated column 'XXX' which is not functionally dependent on columns in GROUP BY clause

Posted at

はじめに

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の設定を無効にして、エラーが出ないようにします。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0