mysql复杂场景的查询

最近没事干,突然想到之前一个问题: mysql查询复杂sql,比如我现在的场景是多个年级每个班级前三名的排序

CREATE TABLE `student` (
  `id` varchar(20) CHARACTER SET latin1 DEFAULT NULL,
  `create_time` datetime(6) DEFAULT NULL,
  `uuid` varchar(100) CHARACTER SET latin1 DEFAULT '',
  `score` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

 

插入数据:

 

insert into `student` (`id`, `create_time`, `uuid`, `score`) values('1','2020-03-04 13:45:50.000000','1class','82');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('2','2020-03-05 13:46:02.000000','1class','95');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('3','2020-03-11 13:45:58.000000','1class','82');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('4','2020-03-22 13:46:04.000000','1class','40');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('5','2020-03-05 13:46:15.000000','1class','20');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('6','2020-03-02 13:46:07.000000','2class','95');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('7','2020-03-25 13:46:12.000000','2class','40');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('8','2020-04-02 13:46:18.000000','2class','3');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('9','2020-03-12 13:46:23.000000','2class','60');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('10','2020-03-12 13:46:21.000000','2class','10');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('11','2020-02-26 13:46:29.000000','3class','70');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('12','2020-03-03 13:46:26.000000','3class','60');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('13','2020-02-25 13:46:32.000000','3class','40');
insert into `student` (`id`, `create_time`, `uuid`, `score`) values('14','2020-03-21 13:46:34.000000','3class','90');

 

这个时候我要查询每个班级前3名的分数,执行sql如下:

SELECT t.uuid
    , t.score
    , t.create_time
    , t.rn
     FROM (
SELECT *
FROM (
    SELECT l1.*
        , IF(@prev = l1.uuid, @rank := @rank + 1, @rank := 1) AS rn
        , @prev := l1.uuid
    FROM student l1
    JOIN ( SELECT @prev := NULL ) init
    ORDER BY l1.uuid
        , l1.score DESC
) l2
WHERE l2.rn <= 3 ) as t

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值