在 mysql 5.7 中,用group by 查询时抛出如下异常:
Expression #1 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'xxx'
which is not functionally dependent on columns in
GROUP BY clause; this is incompatible with
sql_mode=only_full_group_by
MySQL 5.7.5 实现了对功能依赖的检测。如果启用了only_full_group_by SQL模式(在默认情况下是这样),那么 MySQL 就会拒绝选择列表、条件或顺序列表引用的查询,这些查询将引用组中未命名的非聚合列,而不是在功能上依赖于它们。(在5.7.5之前,MySQL没有检测到功能依赖项,only_full_group_by在默认情况下是不启用的。关于前5.7.5行为的描述,请参阅 MySQL 5.6参考手册。)
修改 app/database.php
文件中 mysql
参数,改动如下:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null,
],
在 mysql 命令行执行如下命令:
mysql> select @@sql_mode;
结果为:
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,
NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,
NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
A.执行命令
mysql> set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
B.修改 mysql 配置文件 my.cnf
sudo vim /etc/mysql/conf.d/mysql.cnf
设置
[mysqld]
sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,
ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,
NO_ENGINE_SUBSTITUTION
保存并重启
sudo service mysql restart
select 列名 from 表名 group by 列名
使用聚合函数,例如 sum()
select 列名,sum(列名) from 表名 group by 列名
原文: http://yiqiao.me/articles/5/laravel-uses-group-by-to-report-errors
版权声明: 自由转载-非商用-非衍生-保持署名 (创意共享3.0许可证)