通过变量巧实现排名处理

文章描述了一个SQL查询案例,用于获取学生在特定表中的分数排名,原始查询存在逻辑错误。作者修复了这个问题,通过子查询计算上一条成绩并调整排名。重点在于数据库操作和SQL查询语句的优化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

时间:2019-04-20 11:26:35

图片.png

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

CREATE TABLE `user` (

  `id` int(10) NOT NULL AUTO_INCREMENT,

  `namevarchar(50) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4;

CREATE TABLE `score` (

  `user_id` int(10) NOT NULL,

  `subject` varchar(255) DEFAULT NULL,

  `score` int(2) DEFAULT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO `test`.`score`(`user_id`, `subject`, `score`) VALUES (1, '语文', 90);

INSERT INTO `test`.`score`(`user_id`, `subject`, `score`) VALUES (1, '数学', 96);

INSERT INTO `test`.`score`(`user_id`, `subject`, `score`) VALUES (3, '语文', 91);

INSERT INTO `test`.`score`(`user_id`, `subject`, `score`) VALUES (3, '数学', 92);

INSERT INTO `test`.`score`(`user_id`, `subject`, `score`) VALUES (4, '语文', 91);

INSERT INTO `test`.`score`(`user_id`, `subject`, `score`) VALUES (4, '数学', 92);

INSERT INTO `test`.`user`(`id`, `name`) VALUES (1, 'aaa');

INSERT INTO `test`.`user`(`id`, `name`) VALUES (2, 'bbb');

INSERT INTO `test`.`user`(`id`, `name`) VALUES (3, 'ccc');

INSERT INTO `test`.`user`(`id`, `name`) VALUES (4, 'ddd');

 查学生排名:

1

2

3

4

5

6

7

8

9

10

SELECT

    @rownum :=@rownum + 1 as top_id,

    `user`.name,

    SUM(if(score.score is NULL,0,score.score)) score

FROM

    (SELECT @rownum:=0) r,

    `user`

    LEFT JOIN score ON `user`.id = score.user_id

GROUP BY `user`.id

ORDER BY top_id

图片.png

数据中出现两个183的成绩,按实际情况应该出现两个第二名才对,修改后的sql:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

SELECT 

a.*,

@maxscore '上一条成绩',

if((@maxscore = a.score), @rownum,(@rownum :=@rownum + 1)) as top_id,

@maxscore :=a.score

FROM (

        SELECT

            `user`.name,

            SUM(if(score.score is NULL,0,score.score)) score

        FROM

            `user`

            LEFT JOIN score ON `user`.id = score.user_id

        GROUP BY `user`.id ORDER BY score desc

    ) a, (SELECT @rownum:=0,@maxscore:=0) r

注意:这里写了一个子查询,直接@maxscore :=SUM(if(score.score is NULL,0,score.score)) 赋值此变量一直是0.00000,不知道是什么原因,所以只能写子查询了。。

图片.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值