详细解析:mysql实现分组查询每个班级的前三名

8.2 mysql实现分组查询每个班级的前三名

先上答案

select a.class,a.score from student a 
where 
(select 
 count(*) 
 from 
 student 
 where a.class=class and a.score<score)
 <3
order by 
a.class, a.score 
desc;

解析:

对于上面的sql语句,将其拆分为两部分:

主查询:

select a.class,a.score from student a 
where 
  condition
order by a.class, a.score desc;

主查询很好理解,对于a中的每一行,只要它满足condition条件,那就把它作为结果,排序输出。

那么什么样的一样可以满足condition条件呢?

子查询 condition:

(select count(*)  from  student  where a.class=class and a.score<score) <3

可以看到,在子查询中,对于a中的每一行,记为传入行,都与student表中的每一行(记为内部行)进行一次比较,有两个条件:

  • 传入行和传出行类别相同;
  • 传入行的分数小于内部行的分数。

当这两个条件满足,就说明这个表中这一条内部行的分数比传入行大。

子查询的输出为count(*),也就是要统计满足上述两个条件的行数的条目数。有N条满足,就说明这个表中有N条数据大于该传入行,也就是传入行的分数在这一类中排第N+1。

那么再加一个限定条件<3,也就是取前三名。

这样结果就显然易见了。

发布了63 篇原创文章 · 获赞 14 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/dong_W_/article/details/105598818