SELECT list is not in GROUP BY clause and contains nonaggregated column

Posted 咖啡&牛奶的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SELECT list is not in GROUP BY clause and contains nonaggregated column相关的知识,希望对你有一定的参考价值。

问题:

SELECT list is not in GROUP BY clause and contains nonaggregated column

 

原因:

举个例子,有这么一个查询语句:

SELECT

    user_name as name,

    user_age as age

FROM

    user

GROUP BY

    user_age

 

mysql5.7之后,sql_mode中ONLY_FULL_GROUP_BY模式默认设置为打开状态,这样的话,你select(查询)的字段都要包含在group by中,比如例子中,根据user_age进行分组,但是你查询的时候包含了user_name和user_age两个字段,而user_name不包含在group by当中,所以就会报错。

比如,表中的数据是这样的:

user_name user_age
小明 23
小东 23

 

 

 

 

当你使用group by通过user_age进行分组,那么分组结果只有23,但是23中user_name有小明和小东,那么究竟是返回(小明,23)还是(小东,23)就存在歧义了

除非把语句中的user_name去掉,如下所示:

SELECT

  user_age as age

FROM

  user

GROUP BY

  user_age

那么如果要查询user_name和user_age两个字段,并且根据user_age分组应该怎么解决呢?解决方法如下。

 

解决方法:

一种方法是通过临时或者修改配置文件的方式去掉ONLY_FULL_GROUP_BY 模式,这里就不讲了。这里讲另一种方法:通过使用any_value()函数来解决。

把原来的语句改写成如下形式:

SELECT

  any_value(user_name) as name,

  user_age as age

FROM

  user

GROUP BY

  user_age

如果有查询更多字段,形式如下:

SELECT

  any_value(user_name) as name,

  any_value(user_id) as id,

  user_age as age

FROM

  user

GROUP BY

  user_age

以上是关于SELECT list is not in GROUP BY clause and contains nonaggregated column的主要内容,如果未能解决你的问题,请参考以下文章

SELECT list is not in GROUP BY clause and contains nonaggregated

SELECT list is not in GROUP BY clause and contains nonaggregated column

SELECT list is not in GROUP BY clause and contains

linux下order by 报出ORDER BY clause is not in SELECT list

MySQL出现“SELECT list is not in GROUP BY clause and contains xxx”错误提示

mysql问题解决SELECT list is not in GROUP BY clause and contains nonaggregated column