Mysql Top N

此MYSQL基于5.7, only_full_group_by模式

Having 和 Where 区别 : https://blog.csdn.net/jdjh1024/article/details/76647866

准备数据

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 1

查询每门课程分数最高的学生以及成绩

1.连接查询

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

2.子查询

select name,course,score from test1 a where score = (select max(score) from test1 where a.course=test1.course)

TOP N

1.连接查询-某门课程的TOP-N

select a.name,a.course,a.score
    from test1 a left join test1 b on a.course=b.course and a.score<b.score where a.course = '语文'
    group by a.name,a.course,a.score
    having count(b.id)<2
    order by a.course,a.score desc

1.连接查询-各个课程的TOP-N

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

 

3.子查询-各个课程的第一名

select *
    from test1 a
    where 0 = (select count(*) from test1 where course=a.course and score>a.score)
    order by a.course,a.score desc;

4.子查询-各个课程的第二名
select *
    from test1 a
    where 1 = (select count(*) from test1 where course=a.course and score>a.score)
    order by a.course,a.score desc;

 

5.子查询-各个课程的TOP2
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;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值