MySQL Group By 查询,错误1055

MySQL Group By 查询,错误1055

错误

> 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column ‘flowcenter_idm.m_flow_param.rank’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

在这里插入图片描述

原因

mysql从5.7.5开始默认开启 ONLY_FULL_GROUP_BY,也就是说只要使用的字段就必须在 Group By 存在,否则报错。

举例:

  1. 如上图,错误原因是,Order By 中使用的 rankGroup By 中不存在,所以报错
  2. select rank,type FROM m_flow_param GROUP BY type,这种也会报错,因为查询字段 rank,在 Group By 中不存在

解决方法

方法1

保持使用到的字段,都在 Group By 中存在

方法2

关闭 only_full_group_by

SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

方法3

使不在 Group By 中的字段不再为聚合参数
如将上面错误 sql 改为

SELECT
	`type` 
FROM
	m_flow_param 
GROUP BY `type`
ORDER BY MAX(`rank`) ASC

由于使用 Max() 函数,使得 rank 值唯一,不再是聚合集合,所以 sql 成功
在这里插入图片描述

发布了102 篇原创文章 · 获赞 375 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_37143673/article/details/103469246
今日推荐