2011-05-08 67 views
1

我認爲這是best solution。然而,這種查詢是解決不了我的問題 - 我有一個像這樣的表:mysql在羣組之前排序

+--+-------+-----+ 
|id|user_id|score| 
+--+-------+-----+ 
|1 |1  |5 | 
+--+-------+-----+ 
|2 |1  |16 | 
+--+-------+-----+ 
|3 |1  |15 | 
+--+-------+-----+ 

查詢:

SELECT * 
    FROM (`_scorboard`) 
GROUP BY `user_id` 
    HAVING `score` = MAX(score) 
ORDER BY `score` desc 

result 0 rows 

爲什麼它返回0的記錄?

+1

這甚至執行? 'SELECT * ... GROUP BY ...'是一件很奇怪的事情! – 2011-05-08 23:04:54

+0

[這裏](http://stackoverflow.com/questions/5140785/mysql-order-before-group-by/5140943#5140943),這樣的解決方案是由 – alioygur 2011-05-08 23:10:04

+0

給出的,我這樣解決它,但我不認爲(t2.firstname,'',t2.lastname)AS全名 FROM(SELECT * FROM _scorboard ORDER BY score DESC)AS t1 LEFT JOIN _user_profile AS t2 ON(t1。 user_id = t2.user_id) GROUP BY t1.user_id LIMIT 0,20 – alioygur 2011-05-08 23:12:56

回答

3

用途:

SELECT a.* 
    FROM SCOREBOARD a 
    JOIN (SELECT t.user_id, 
       MAX(t.score) AS max_score 
      FROM SCOREBOARD t 
     GROUP BY t.user_id) b ON b.max_score = a.score 
          AND b.user_id = a.user_id 

如果你想那些誰得分最高的表:

SELECT a.* 
    FROM SCOREBOARD a 
    JOIN (SELECT MAX(t.score) AS max_score 
      FROM SCOREBOARD t) b ON b.max_score = a.score 
3

既然你通過1user_id在您的查詢中,MySQL組一個GROUP BY條款首先,選擇任何它喜歡的行。 HAVING子句將應用於這些選定的行。由於所選行可能是MAX的值爲score的那一行,因此查詢返回0結果。

做正確的方法是:

SELECT _scoreboard.* 
    FROM _scoreboard JOIN (SELECT user_id, MAX(score) 
          FROM _scorboard 
          GROUP BY user_id) 
     AS t ON _scoreboard.user_id = t.user_id 
      AND _scoreboard.score = t.score 
ORDER BY _scoreboard.score DESC 
+1

感謝您回答問題!這是我從中學到的東西! :) – 2012-03-06 09:23:34