原始数据

查询每科的最高分数
-- 查询每科最高分数
select stuId,classId,stuName,max(score) from student_score group by classId 错误的结果

这个显然不是对的,或者说不是我们想要的结果,
我们想要的结果是

原因是什么呢?我们知道使用group by分组时,对于有相同的分组字段行会合并成一行,这个时候,如果查询的字段中有非分组字段,非分组字段的数据会读取合并的第一行;
解决思路是:
方案一:
先将分组的classId和max(score)查出来,作为临时数据然后连表查询
select
	a.stuId,
	a.classId,
	a.stuName,
	a.score
from
	student_score a
inner join 
(
	select
		classId ,
		max(score) as score
	from
		student_score
	group by
		classId) b 
on
	a.classId = b.classId
	and a.score = b.score
这种思路是直接匹配数据
还有另外一种思路是,既然非分组是取第一条,那么我们可以按照min还是max来看是用asc还是desc排序
方案二:
因为这里是找最大分数,非分组数据又是取第一条数据,所以我们应该分数倒序
select
	b.stuId,
	b.classId,
	b.stuName,
	b.score
from
	(
	select
		a.stuId,
		a.classId,
		a.stuName,
		a.score
	from
		student_score a
	
	order by
		score desc) b
group by
	b.classId这个时候还是有问题, 因为mysql 5.6之后版本对排序的sql解析做了优化,子查询中的排序是会被忽略的,所以上面的order by id desc未起到作用
现在的执行结果是这样的,其实还是错误的

所以我们要加上having 1 = 1 来让排序生效
select
	b.stuId,
	b.classId,
	b.stuName,
	b.score
from
	(
	select
		a.stuId,
		a.classId,
		a.stuName,
		a.score
	from
		student_score a
	having
		1 = 1
	order by
		score desc) b
group by
	b.classId最后也得到了想要的结果

查询之后发现,limit也能阻止子查询order by被优化,所以这样也可以
select
	b.stuId,
	b.classId,
	b.stuName,
	b.score
from
	(
	select
		a.stuId,
		a.classId,
		a.stuName,
		a.score
	from
		student_score a
	order by
		score desc
	limit 1000) b
group by
	b.classId方案三:
当查询的最大、最小值是唯一的时候,还能够通过这样的来查询
select
	b.stuId,
	b.classId,
	b.stuName,
	b.score
from student_score b where score in
	(
	select
		max(score)
	from
		student_score a
	 group by classId) 
注意,我这里只是演示,如果求分组后的最大分数,且分数都不相同的时候,是可以用这个的,比如最大Id啥之类的,这个是唯一值,可以使用这种方式。我这里因为70分有相同,所以不是很对。



















