MYSQL升级5.7.10后GROUP BY语句出错解决方法

2019-03-19  本文已影响0人  旅行者xy

问题:在使用group by的时候,语句如下:

SELECT * FROM ( SELECT * FROM t_student_level ORDER BY gmt_modified DESC LIMIT 0,1000000000000000 )sl GROUP BY student_id

出现了如下错误:

[Err] 1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sl.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

错误截图.png

这是因为mysql5.7版本默认配置 sql-mode=only_full_group_by,这会限制select查询的列只能和group by后面的列一致,即group by后面只有student_id一列,则select也只能查询student_id列。该模式是为了规范查询效率才存在的。通常,出现这种需求的查询有可能是数据库设计不是很合理,可以先检查加数据库是否可优化,若是没办法更改的话,可以到数据配置文件my.ini中设置sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION",既可使用该语句。

网上有传,可以使用聚合函数来查询更多的列,经过试验,和最初想要获取的数据行数据不一致,除非其他列刚好要获取的即时聚合函数查出来的值,如下:

SELECT student_id,max(other_one) other_one,max(other_two) other_two FROM ( SELECT * FROM t_student_level ORDER BY gmt_modified DESC LIMIT 0,1000000000000000 )sl GROUP BY student_id
这样查出来的other_one和other_two两列的值和student_id不是同一行,是同个组中列的的最大值

上一篇 下一篇

猜你喜欢

热点阅读