SQL表的不同值

时间:2013-10-22 05:08:51

标签: mysql sql greatest-n-per-group

我有这张桌子

enter image description here

我希望得分最高的10个不同的行按降序排列。 所以我试过

SELECT * FROM `highscores` GROUP BY userID  ORDER BY score DESC LIMIT 10  ;

这是不正确的,因为它返回:

enter image description here

然后我尝试了:

SELECT distinct(userID),userName,userLastname,score FROM {高分{1}}

这也是不正确的,因为它并不真正返回基于userID的不同行。

enter image description here

这就是我想要的结果:

enter image description here

我希望保持每位玩家的最高分(不同ORDER BY score DESC ;)为10名第一名玩家。知道我该怎么办?

5 个答案:

答案 0 :(得分:0)

SELECT  a.*
FROM    highscore a
        INNER JOIN
        (
            SELECT  userID, MAX(score) score
            FROM    highscore
            GROUP   BY userID
        ) b ON  a.userID = b.userID 
                AND a.score = b.score
ORDER   BY score DESC
LIMIT   10

但这并不能处理关系。

答案 1 :(得分:0)

In MySQL您可以将DISTINCT运算符与多个列一起使用。所有列的组合将用于定义结果集中行的唯一性。

例如,要从customers表中获取city和state的唯一组合,请使用以下查询:

SELECT DISTINCT州,城市 来自客户 WHERE状态不是NULL 按州,城市订购

答案 2 :(得分:0)

根据您的问题更新:

SELECT h1.* FROM highscores h1
LEFT JOIN highscores h2 ON h1.userId = h2.userId and h1.score < h2.score
WHERE h2.score IS NULL
ORDER BY h1.score DESC
LIMIT 10

另一种方法是:

SELECT h1.* FROM highscores h1
JOIN (
    SELECT userId, max(score) maxScore FROM highscores
    GROUP BY userId
) h2 ON h1.userId = h2.userId and h1.score = h2.maxScore
ORDER BY h1.score DESC
LIMIT 10

答案 3 :(得分:0)

试试这个:

SELECT  userID,userName,userLastname, MAX(score) as score 
 FROM highscores 
  WHERE userID in (
    SELECT distinct userID FROM highscores )
  ORDER BY score DESC
  LIMIT 10;

答案 4 :(得分:0)

正确的查询是:

SELECT userName, userLastname, userID, MAX( score ) 
FROM  `highscores` 
GROUP BY userID
ORDER BY MAX( score ) DESC 
LIMIT 10

感谢EddieJamsession的评论。