1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'gra

报错内容:

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

出现问题缘由:

1、本地MySQL版本为5.5,执行如下查询语句,结果正常:

SELECT * FROM score GROUP BY paper_name; 

1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'gra

2、云服务上安装的MySQL版本为8.0,执行了同样的查询语句,结果报错:

1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'gra

问题解决:

1、我的本意是想通过分组查询,得到有多少种paper_name,但是MySQL8.0好像不支持

SELECT * FROM 某表 GROUP BY 某列; 

2、于是我将SQL语句改为

SELECT paper_name FROM score GROUP BY paper_name; 

1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'gra

1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'gra

都执行成功!

问题分析:

1、我们SQL语句使用GROUP BY,是为了得到某列值有几种,这样的话使用

SELECT 某列 FROM 某表 GROUP BY 某列; 

就是最标准的写法,只得到某列值有几种。

2、对于

SELECT * FROM 某表 GROUP BY 某列;

而言,我们是能得到某列值有几种,但是也查出了其它没啥实质性意义、多余的列,这是不标准的。

3、所以我认为,MySQL5.5对比MySQL8.0(其它版本不清楚,没测试过)对于GROUP BY语句的宽容程度是不同的,MySQL8.0只允许最标准的GROUP BY语句,这就导致了同一SQL语句,不同MySQL版本执行效果不同。我们在书写SQL语句时一定要养成严谨、标准的习惯。