错误1055
来源:3-22 排序

Singularity奇点
2021-06-14
在3-22节最后一个练习,这里有个问题,如果是用MySQL默认的设置会报错
select t1.stu_no, t1.stu_name, sum(t2.score)
from school_student_info t1, school_student_grade t2
where t1.id = t2.student_id
group by t1.stu_no
order by sum(t2.score) desc;
错误是
1055 - Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘my_data_base.t1.stu_name’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
group by 的col是 stu_no, 但是显示的col包括stu_name, 但是它不包括在group by的语句里,所以和sql_mode的only_full_group_by不匹配,应该要设置一下
mysql > SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
详细的看stackoverflow
如果用MariaDB就没有这个问题。讲师在这里应该说明一下
写回答
2回答
-
979811597
2022-04-10
对。否则只能使用以下两种写法
1- group by 中 包含t1.stu_no 和 t1.stu_name;
SELECT t1.stu_no, t1.stu_name, SUM(t2.score) as 总分 FROM school_student_info t1, school_student_grade t2 where t1.id=t2.student_id GROUP BY t1.stu_no,t1.stu_name;
2-group by 使用id 进行分组
SELECT t1.stu_no, t1.stu_name, SUM(t2.score) as 总分 FROM school_student_info t1, school_student_grade t2 where t1.id=t2.student_id GROUP BY t1.id;
012022-04-13 -
NavCat
2021-06-15
感谢同学的反馈,这个问题其实在Oracle数据库里面也存在,在使用GROUP BY进行分组之后,SELECT子句中出现的列只能是GROUP BY 中的列或者是函数的值
00
相似问题