PHP MYSQL group ranking query

倾然丶 夕夏残阳落幕 提交于 2019-11-28 12:18:31

问题


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.


回答1:


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 


来源:https://stackoverflow.com/questions/29451275/php-mysql-group-ranking-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!