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

posted @ 2021-09-14 22:11  咖啡&牛奶  阅读(511)  评论(0编辑  收藏  举报