有时会碰到一些需求,查询分组后的最大值,最小值所在的整行记录或者分组后的top n行的记录,像在hive中是有窗口函数的,能够经过它们来实现,可是MySQL没有这些函数,可经过下面的方法来实现函数
一、准备url
create table `test1` ( `id` int(11) not null auto_increment, `name` varchar(20) default null, `course` varchar(20) default null, `score` int(11) default null, primary key (`id`) ) engine=innodb auto_increment=10 default charset=utf8 insert into test1(name,course,score) values ('张三','语文',80), ('李四','语文',90), ('王五','语文',93), ('张三','数学',77), ('李四','数学',68), ('王五','数学',99), ('张三','英语',90), ('李四','英语',50), ('王五','英语',89);
二、TOP 1spa
需求:查询每门课程分数最高的学生以及成绩code
实现方法:能够经过自链接、子查询来实现,以下blog
a、自链接实现rem
select a.name,a.course,a.score from test1 a join (select course,max(score) score from test1 group by course) b on a.course=b.course and a.score=b.score;
执行效果以下get
b、子查询实现博客
select name,course,score from test1 a where score=(select max(score) from test1 where a.course=test1.course);
执行效果以下数学
也能够用下面这个子查询实现it
select name,course,score from test1 a where not exists(select 1 from test1 where a.course=test1.course and a.score < test1.score);
执行效果以下
三、TOP N
需求:查询每门课程前两名的学生以及成绩
实现方式:使用union all、自身左链接、子查询、用户变量等方式实现
a、使用union all实现
(select name,course,score from test1 where course='语文' order by score desc limit 2) union all (select name,course,score from test1 where course='数学' order by score desc limit 2) union all (select name,course,score from test1 where course='英语' order by score desc limit 2);
执行效果以下
b、使用自身左链接
select a.name,a.course,a.score from test1 a left join test1 b on a.course=b.course and a.score<b.score group by a.name,a.course,a.score having count(b.id)<2 order by a.course,a.score desc;
执行效果以下
c、使用子查询
select * from test1 a where 2>(select count(*) from test1 where course=a.course and score>a.score) order by a.course,a.score desc;
执行效果以下
d、使用用户变量
set @num := 0, @course := ''; select name, course, score from ( select name, course, score, @num := if(@course = course, @num + 1, 1) as row_number, @course := course as dummy from test1 order by course, score desc ) as x where x.row_number <= 2;
执行效果以下
若是,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的【推荐】。
若是,您但愿更容易地发现个人新博客,不妨点击一下左下角的【关注我】。
若是,您对个人博客所讲述的内容有兴趣,请继续关注个人后续博客,我是【刘超★ljc】。
本文版权归做者,禁止转载,不然保留追究法律责任的权利。