原sql: select id,pl_hit_rule_code from p_l_inspect_hit_rule GROUP BY pl_hit_rule_code
报错信息:[Err] 1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'syngenta.p_l_inspect_hit_rule.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
解决办法1:使用函数ANY_VALUE()包含报错字段
MySQL有any_value(field)函数,它主要的作用就是抑制ONLY_FULL_GROUP_BY值被拒绝。
这样sql语句不管是在ONLY_FULL_GROUP_BY模式关闭状态还是在开启模式都可以正常执行,不被mysql拒绝。
any_value()会选择被分到同一组的数据里第一条数据的指定列值作为返回数据。
官方有介绍,地址:https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
select ANY_VALUE(id),pl_hit_rule_code FROM p_l_inspect_hit_rule GROUP BY pl_hit_rule_code;即可解决。
升级改造一下,如果原sql需要根据日期排序,升级sql如下:
select ANY_VALUE(a.id),a.pl_hit_rule_code from (SELECT id,pl_hit_rule_code FROM p_l_inspect_hit_rule ORDER BY create_time) a GROUP BY a.pl_hit_rule_code
利用子查询+ANY_VALUE()即可解决。
解决办法2:使用表连接查询
select p1.id,p1.pl_hit_rule_code from p_l_inspect_hit_rule p1 JOIN
(select MIN(id) as id,pl_hit_rule_code from p_l_inspect_hit_rule GROUP BY pl_hit_rule_code) p2
ON p1.id = p2.id AND p1.pl_hit_rule_code = p2.pl_hit_rule_code
利用min函数+表连接
其他解决办法可通过更改配置改变sql_mode
参考MySQL错误-this is incompatible with sql_mode=only_full_group_by完美解决方案_格子衫111的博客-CSDN博客