Home > Database > Mysql Tutorial > body text

MySQL parallel ranking and sequential ranking query

步履不停
Release: 2019-07-01 18:05:48
Original
6482 people have browsed it

MySQL parallel ranking and sequential ranking query

Prepare.

创建一张叫scores的表,内容如下。因为测试排名,所以就用最简单的结构。
Copy after login
##199 2803874605806need.
id score
##99
获取分数排名,要求并列排名。如果两个分数相同,则两个分数排名(rank)相同。名次之间不应该有“间隔”。
Copy after login

The results are as follows.

##idscorerank199169913872280358034604sql statement
select id, score, (select count(distinct(score)) from scores as b where b.score > a.score ) + 1 as rank from scores as a order by rank;
先把结果拿出来,然后再分析怎么思考这个问题。这里的查询关键字我都没有大写,个人习惯!应该是要大写的。
Copy after login
Analysis.

按照上面的需求,我们可以知道我们是要做一个按照分数(score)查询的一个功能,只不过是要给排序好的结果加上一个我们想要的名次。
我们笨想,我们要想知道某个分数排第几名,是不是知道有几个比它大就行了。如果有零个比它大的,那么它就是第一名,如果只有一个比它大,
那么它就是第二名。以此类推就好了。
那么我们来分析上面的sql语句。它就是把socres表分成了俩个一样的表,a 表,b表。然后通过子查询去查rank的值。
第一步:select id,score, rank from scores order by rank;我们查询我们要的信息,但是我们scores表中没有rank这个字段,所以就要分成俩个一
       样的表,做子查询,来查rank。
第二步:select id,score,(select count(score) from scores as b where b.score > a.score) + 1 as rank from scores as a order by rank;上面说过了
       如果0个比某分数大,那么它就是第一名。所以我们要再查询的个数上加1。结果如下:
Copy after login

我们发现结果不是我们预期的。因为我们还没有去重。比87大的有俩个都是99,那么87的rank就是2+1=3,而我们要的排名连续不断的。所以用distinct
关键字去重。
第三步:select id, score, (select count(distinct(score)) from scores as b where b.score > a.score ) + 1 as rank from scores as a order by rank;
Copy after login

MySQL parallel ranking and sequential ranking query

Sequential ranking expected resultsMySQL parallel ranking and sequential ranking query

顺序排名我们就按照score字段倒序查询即可,只不过是用msyql的变量去做rank。mysql中的变量是用‘@’跟上变量名称。@rowNum 
php中我们用$rowNum。mysql中赋值用 := 来赋值。(select @rowNum :=0) r 是给变量@rowNum一个初始值为0。这个很好理解。就是
按照我们要排名的字段倒序去查询,再用mysql变量给每一条结果加一个排列序号。
Copy after login

sql statementMySQL parallel ranking and sequential ranking query

select t.id, t.score,@rowNum := @rowNum +1 as rank from (select @rowNum :=0) r, scores as t order by t.score desc ;
Copy after login
Result

For more technical articles related to SQL, please visit the MySQL parallel ranking and sequential ranking querySQL Tutorial

column to learn!

The above is the detailed content of MySQL parallel ranking and sequential ranking query. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!