IT编程 > 数据库 > Mysql

LeetCode——Rank Scores

29人参与2019-10-09

write a sql query to rank scores. if there is a tie between two scores, both should have the same ranking. note that after a tie, the next ranking number should be the next consecutive integer value. in other words, there should be no "holes" between ranks.

+----+-------+
| id | score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
for example, given the above scores table, your query should generate the following report (order by highest score):

+-------+------+
| score | rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

此题,其本质就是赋值行号(需要注意分数相同的情景).

在实践过程中,初版答案如下所示:

# write your mysql query statement below
select 
    a.score as score,
    (select count(distinct b.score) from scores b where b.score >= a.score) as rank
from scores a order by a.score desc;

此处,使用select count来统计行号,注意使用distinct来区分相同分数.
但是,此解题方案的效率较差,sql运行肯定是越快越好.
因此,在sql中引入变量来赋值行号,以替代耗时的select count操作.

# write your mysql query statement below
select 
    score,
    @row := @row + (@pre <> (@pre := score)) as rank
from scores, (select @row := 0, @pre := -1) t
order by score desc;

此处,查询是在scores与临时表之间进行cross join.
此外,使用临时变量(@row,@pre)记录行号.
tips:

通过以上改进,mysql的运行效率得到了较大的提高.

您希望与广大热心网友互动!!点此进行留言回复

相关推荐

LeetCode——Rank Scores

10-09

mysql数据表按照某个字段分类输出

06-05

浅谈MyISAM 和 InnoDB 的区别与优化

07-04

简单介绍下MYSQL的索引类型

06-02

mysql8.0.15安装

04-08

MySql自定义函数-关于保留小数位的特殊需求

09-30

深入了解SQL注入

06-07

ERROR 1050 (42S01): Table xxx already exists

06-21

在大数据情况下MySQL的一种简单分页优化方法

06-04

24H玩转 Grafana 被工程师称相当专业,如何做到?

10-09

最近更新

Linux搭建MySQL主从

10-20

MySQL实战45讲

10-20

“GIS DICTIONARY A-Z” 查询页面开发(2)——INSERT INTO数据库

10-20

MySQL如何进行索引重建操作?

10-20

MySQL truncate含有外键约束的条目报错

10-20

MySQL复制从库建立-xtracebackup方式

10-19

Python学习日记(四十) Mysql数据库篇 八

10-19

mysql查询表大小

10-19

MySQL修炼之路一

10-19

MySQL修炼之路二

10-19

网友评论

已有0条评论