错误提示
MySQLdb._exceptions.OperationalError: (1055, “Expression #2 of SELECT
list is not in GROUP BY clause and contains nonaggregated column
‘train.course_study.company_id’ which is not functionally dependent on
columns in GROUP BY clause; this is incompatible with
sql_mode=only_full_group_by”)
是MySQL5.7以上版本一个属性配置变更导致的问题
解决办法
第一种方式:
在 group by 后面加上要查询的非聚合字段, 比如我这里加上 company_id,相当于通过 user_id+comapny_id 来分组,因为user_id和company_id 是多对一关系,所以 分组查询的时候两者返回的结果是一样的。
select user_id, company_id, sum(learn_time) from student_user group by user_id, company_id
第二种方式:
使用 any_value 函数, 在非聚合字段上使用函数
select user_id, any_value(company_id), sum(learn_time) from student_user group by user_id
第三种方式:
将sql_mode配置中的ONLY_FULL_GROUP_BY去掉, 重启MySQL服务,当然不建议去掉这个配置。这样可以保证你写的SQL更严谨