问题
$users = DB::table('users')->groupBy('gender')->select(DB::raw('count(*) as num,id'))->get();
报错
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'blog.laravel_users.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select count(*) as num,id from `laravel_users` group by `gender`)
报错原因
sql中select后面的字段必须出现在group by后面,或者被聚合函数包裹,不然会抛出上面的错误 如以下sql
解决方法1
- 找配置文件 /etc/mysql/my.cnf
- 修改sql_mode 的值, sql_mode 是配置在[mysqld]下面的
解决方法2
- MySQL5.7之后,sql_mode中ONLY_FULL_GROUP_BY模式默认设置为打开状态。
- ONLY_FULL_GROUP_BY的语义就是确定select target list中的所有列的值都是明确语义,简单的说来,在此模式下,target list中的值要么是来自于聚合函数(sum、avg、max等)的结果,要么是来自于group by list中的表达式的值
- MySQL提供了any_value()函数来抑制ONLY_FULL_GROUP_BY值被拒绝
- any_value()会选择被分到同一组的数据里第一条数据的指定列值作为返回数据
$users = DB::table('users')->groupBy('gender')->select(DB::raw('count(*) as num,any_value(id)'))->get();