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

Mor*_*ork 2 mysql sql

假设我有一个名为Gamers的桌子. 玩家包含列GamerID,GameID,Score.

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

例如,

|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
Run Code Online (Sandbox Code Playgroud)

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

Boo*_*eus 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;
Run Code Online (Sandbox Code Playgroud)

这将输出:

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

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

create temporary table games_score (
 SELECT max(score) as maxscore, gameid FROM gamers GROUP BY gameid
);
Run Code Online (Sandbox Code Playgroud)

然后:

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;
Run Code Online (Sandbox Code Playgroud)

或者一个观点:

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

然后:

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;
Run Code Online (Sandbox Code Playgroud)


Mos*_*cho 5

尝试这个:

select g1.* from gamers g1
left join gamers g2
on g1.gameId = g2.gameId and g1.score < g2.score
where g2.score is null
Run Code Online (Sandbox Code Playgroud)

结果提供了以下数据:

+---------+--------+-------+
| GAMERID | GAMEID | SCORE |
+---------+--------+-------+
|       4 |      1 |    90 |
|       5 |      2 |    40 |
|       8 |      3 |    30 |
+---------+--------+-------+
Run Code Online (Sandbox Code Playgroud)