mysql SELECT在单个表中的每个类别中最佳

时间:2012-02-17 02:44:48

标签: mysql sql

假设我有一张名为Gamers的桌子。 游戏玩家包含GamerIDGameIDScore列。

我有兴趣选择每场比赛中得分最高的球员。

例如,

|Gamers
|-------------------------
|GamerID | GameID | Score
|1       | 1      | 10
|2       | 1      | 10
|3       | 1      | 10
|4       | 1      | 90
|5       | 2      | 40
|6       | 2      | 10
|7       | 3      | 10
|8       | 3      | 30

在查询之后,我希望得到GamerID 4,5和8的行。这样做的查询是什么?

5 个答案:

答案 0 :(得分:6)

试试这个:

SELECT gamers.*
FROM gamers
INNER JOIN 
 (SELECT 
   max(score) as maxscore, 
   gameid from gamers
   GROUP BY gameid) AS b
ON (b.gameid = gamers.gameid AND b.maxscore=gamers.score) ;
ORDER BY score DESC, gameid;

这将输出:

+---------+--------+-------+
| gamerid | gameid | score |
+---------+--------+-------+
|       4 |      1 |    90 |
|       5 |      2 |    40 |
|       8 |      3 |    30 |
+---------+--------+-------+
3 rows in set (0.00 sec)

您可以执行的另一个选项是创建临时表或视图(如果您不喜欢子查询)。

create temporary table games_score (
 SELECT max(score) as maxscore, gameid FROM gamers GROUP BY gameid
);

然后:

SELECT gamers.* 
FROM gamers 
INNER JOIN games_score AS b ON (b.gameid = gamers.gameid AND b.maxscore=gamers.score) 
ORDER BY score DESC, gameid;

或者观点:

create or replace view games_score AS 
SELECT max(score) as maxscore, gameid FROM gamers GROUP BY gameid;

然后:

SELECT gamers.* 
FROM gamers 
INNER JOIN games_score AS b ON (b.gameid = gamers.gameid AND b.maxscore=gamers.score) 
ORDER BY score DESC, gameid;

答案 1 :(得分:4)

试试这个:

SELECT a.GameID, a.GamerID, a.Score
FROM Gamers a INNER JOIN
    (
        SELECT s.GameID, MAX(s.Score) AS Maxx
        FROM Gamers s
        GROUP BY s.GameID
    ) b ON (a.GameID = b.GameID) AND (a.Score = b.Maxx) 
ORDER BY GameID;

答案 2 :(得分:4)

试试这个:

select g1.* from gamers g1
left join gamers g2
on g1.gameId = g2.gameId and g1.score < g2.score
where g2.score is null

提供数据的结果:

+---------+--------+-------+
| GAMERID | GAMEID | SCORE |
+---------+--------+-------+
|       4 |      1 |    90 |
|       5 |      2 |    40 |
|       8 |      3 |    30 |
+---------+--------+-------+

答案 3 :(得分:2)

您可以使用子选项完成此操作,如下所示:

SELECT GameID, GamerID, Score
FROM Gamers
WHERE Score = (
     SELECT
     MAX(scores.Score)
     FROM Gamers AS scores
     WHERE scores.GameID = Gamers.GameID
)
GROUP BY GameID

经过测试:

CREATE TABLE Gamers (
  GamerID int(11) NOT NULL,
  GameID int(11) NOT NULL,
  Score int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO Gamers (GamerID, GameID, Score) VALUES
(1, 1, 10),
(2, 1, 10),
(3, 1, 10),
(4, 1, 90),
(5, 2, 40),
(6, 2, 10),
(7, 3, 10),
(8, 3, 10);

当然,在两名玩家为特定游戏获得相同分数的情况下,这并不理想。

答案 4 :(得分:0)