在MySQL使用group by报错:
select courseid,score,stuid from score group by courseid;
[Err] 1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'ssm.score.stuid'
which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by
select的字段出现了group by中没有出现的字段,所以报错;在sql_mode=only_full_group_by时,可以允许下列写法:
select a,b [聚合函数(c)] from table_name group by a,b
在该列子中:group by 有2个字段:a, b;所以select字段的的合法写法:
select a [聚合函数(c)] /select b [聚合函数(c)] /select a,b [聚合函数(c)]
要想select字段不受group by字段的限制只需要设置一下sql_mode即可;
1.查出sql_mode 的值
select @@global.sql_mode;
//ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
将值复制出来,不同版本sql_mode的值可能不一样,根据自己查询复制值就行了
2.将ONLY_FULL_GROUP_BY去掉,重新设置sql_mode的值
set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
这种方法在重启MySQL之后,仍然会恢复到之前的模式;想要永久生效,需要使用下面的方法:在ini文件中添加:
[mysqld]
sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'