PHP MYSQL组排名查询 [英] PHP MYSQL group ranking query

查看:72
本文介绍了PHP MYSQL组排名查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

CREATE TABLE `players` (
 `pid` int(2) NOT NULL AUTO_INCREMENT,
 `name` varchar(50) NOT NULL,
`team` varchar(20) NOT NULL,
`age` int(2) NOT NULL,
PRIMARY KEY (`pid`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;


INSERT INTO `players` (`pid`, `name`, `age`, `team`) VALUES
(1, 'Samual', 25, 'aa'),
(2, 'Vino', 20, 'bb'),
(3, 'John', 20, 'dd'),
(4, 'Andy', 22, 'cc'),
(5, 'Brian', 21, 'dd'),
(6, 'Dew', 24, 'xx'),
(7, 'Kris', 25, 'qq'),
(8, 'William', 26, 'cc'),
(9, 'George', 23, 'nn'),
(10, 'Peter', 19, 'aa'),
(11, 'Tom', 20, 'aa'),
(12, 'Andre', 20, 'aa');

在上表中,我希望该查询以分数的降序获取球员的排名.

In the above table, I want this query to fetch the ranking of the players in descending order of their scores.

SELECT pid, name, age, team, rank FROM
(SELECT pid, name, age, team,
@curRank := IF(@prevRank = age, @curRank, @incRank) AS rank, 
@incRank := @incRank + 1, 
@prevRank := age
FROM players p, (
SELECT @curRank :=0, @prevRank := NULL, @incRank := 1
) r 
ORDER BY age DESC) s WHERE team='aa'

它给了我以下结果:

Name        |     Age    | Rank  
####--------------------------------   
Samual      |     25     | 2    
Tom         |     20     | 8    
Andre       |     20     | 8    
Peter       |     19     | 12  

但是我希望以这种方式返回结果:

But I want the results to be returned in this manner:

Name        |     Age    | Rank  
####--------------------------------   
Samual      |     25     | 1    
Tom         |     20     | 2    
Andre       |     20     | 2    
Peter       |     19     | 4   

因此,进行查询以给出特定组内的排名.

Therefore, making the query to give me the rank within a particular group.

推荐答案

您需要将查询中的where子句移动为

You need to move the where clause inside the query as

SELECT pid, 
name, 
age, 
team, 
rank 
FROM (
 SELECT pid, name, age, team,
 @curRank := IF(@prevRank = age, @curRank, @incRank) AS rank, 
 @incRank := @incRank + 1, 
 @prevRank := age
 FROM players p, (SELECT @curRank :=0, @prevRank := NULL, @incRank := 1) r
 WHERE team='aa'
 ORDER BY age DESC
) s 

这篇关于PHP MYSQL组排名查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆