您的位置:首页 > 数据库 > MySQL

MySQL: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column '

2017-09-14 11:09 1001 查看
http://www.zhimengzhe.com/shujuku/other/252133.html

今天在执行MySQL中sql语句的时候报错了,执行的sql语句:
SELECT
prov_desc,
area_desc,
month_id,
MAX(total_fee)AS max_total,
FROM
sss
WHERE
prov_id = '075'
OR prov_id IN('017')
AND month_id IN('201207')
GROUP BY
prov_id,
prov_desc,
prov_ord,
area_desc,
area_ord
HAVING
MAX(total_fee)> 100
ORDER BY
prov_ord DESC,
area_ord


错误提示如下:
Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sss.month_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by


​ 认真看错误的提示发现是在group by中的字段比较selelct中的字段差了一个month_id, 而正好是month_id报错。
this is
incompatible with sql_mode=only_full_group_by
这句话提示了这违背了mysql的规则,only fully group by,也就是说在执行的时候先分组,根据查询的字段(select的字段)在分组的内容中取出,所以查询的字段全部都应该在group by分组条件内;一种情况例外,查询字段中如果含有聚合函数的字段不用包含在group by中,就像我上面的MAX(total_fee),至于为什么,我也不抬明白。 

​ 后来发现Order by排序条件的字段也必须要在group by内,看此大神的博文解释之后豁然开朗,排序的字段也是从分组的字段中取出。 不明白的可以去看一下。

解决办法:select字段必须都在group by分组条件内(含有函数的字段除外)。(如果遇到order by也出现这个问题,同理,order by字段也都要在group by内)。

以上就是MySQL: Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sss的全文介绍,希望对您学习和使用数据库有所帮助.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐