Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column
环境
MySQL:8+
在执行类似这样的语句时:
SELECT * from template_detail a group by template_id;
然后报错了:
1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains
nonaggregated column 'ssm.template_detail.id' which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by, Time: 0.0000
具体原因是:
ONLY_FULL_GROUP_BY: 对于GROUP BY聚合操作,如果在SELECT中的列,没有在GROUP
BY中出现,那么这个SQL是不合法的,因为列不在GROUP BY从句中
也就是说,select 后面的字段应该是group 中出现的:
SELECT template_id from template_detail a group by template_id;
这样就成功了。
但是实际情况下,我们肯定不是只获取到这么一个字段,需要获取多个,那么该如何解决呢?
修改配置的方法
方法一
执行下面的语句
select @@global.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
去掉ONLY_FULL_GROUP_BY,重新设置值。
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';
本人实践:无论是重启MySQL,还是不重启MySQL,都不行。
方法二
sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
执行完成后,然后再执行上面的语句,发现成功了。(不用重启MySQL,猜测,如果真的重启MySQL,配置肯定会被还原,所以别重启)。
方法三
MySQL
有any_value(field)
函数,他主要的作用就是抑制ONLY_FULL_GROUP_BY
值被拒绝
官方有介绍,地址:https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
我们可以把select
语句中查询的属性(除聚合函数所需的参数外),全部放入any_value(field)函数中;
例如:
SELECT a.template_id,any_value(a.detail) detail, any_value(a.id) id
from template_detail a
group by template_id
这样sql
语句不管是在ONLY_FULL_GROUP_BY
模式关闭状态还是在开启模式都可以正常执行,不被mysql
拒绝。
从上面的语句中也能看出来,每个显示的字段都要写any_value(...)
,这样其实很麻烦。
个人偏向修改配置吗,一次性解决的那种,只是方法一,我自己没有测试出来,本地环境,用方法二也可以。
参考地址:
SELECT list is not in GROUP BY clause and contains nonaggregated column
上一篇: Angularjs自定义一个可输入的下拉框组件(代码示例)
下一篇: 如何伸展一个元素到窗口高度
推荐阅读
-
解决大于5.7版本mysql的分组报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated
-
解决大于5.7版本mysql的分组报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'userinfo.
-
mysql从5.6升级到5.7后出现 Expression #1 of ORDER BY clause is not in SELECT list,this is incompatible with DISTINCT
-
Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregate
-
ERROR 1055 (42000): Expression #3 of SELECT list is not in GROUP BY clause ... 的错误
-
报错 1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated
-
1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains解决
-
idea报错 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggre
-
linux上,mysql使用聚合函数group by 时报错:SELECT list is not in GROUP BY clause and contains nonaggre的问题
-
解决大于5.7版本mysql的分组报错Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated