简体   繁体   中英

PHP MYSQL group ranking query

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'

It gave me the result below:

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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM