簡體   English   中英

SQL表的不同值

[英]Distinct values of an SQL Table

我有這張桌子

在此處輸入圖片說明

我想要分數最高的10個不同行按降序排列。 所以我嘗試了

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

這是不正確的,因為它返回:

在此處輸入圖片說明

然后我嘗試了:

SELECT distinct(userID),userName,userLastname,score FROM ORDER BY score DESC ;

這也不是正確的,因為它實際上並不會基於userID返回不同的行。

在此處輸入圖片說明

這就是我想要的結果:

在此處輸入圖片說明

我想保持10位第一位玩家的最高得分(每個userID均不同)。 知道我該怎么做嗎?

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

但是,這不處理關系。

在MySQL中,您可以將DISTINCT運算符與多個列一起使用。 所有列的組合將用於定義結果集中行的唯一性。

例如,要從客戶表中獲得城市和州的唯一組合,請使用以下查詢:

SELECT DISTINCT狀態,城市從客戶那里,狀態不為空ORDER BY狀態,城市

根據您的問題更新:

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

嘗試這個:

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

正確的查詢是:

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

感謝EddieJamsession的評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM