2012-07-06 162 views
1

我有以下數據的用戶表:MySQL查詢排名

 
+----+------------+--------------+--------------+--------------+ 
| id | name  | points_game1 | points_game2 | points_game3 | 
+----+------------+--------------+--------------+--------------+ 
| 1 | player 1 |   10 |   0 |   5 | 
| 2 | player 2 |   0 |   25 |   0 | 
| 3 | player 3 |   30 |   3 |   0 | 
| 4 | player 4 |   0 |   0 |   20 | 
+----+------------+--------------+--------------+--------------+ 

我希望能夠表現出整體的行列,其中排名被定義爲總體最高得分,而不是排名每場比賽。所以在上面的例子中,我會用什麼查詢,顯示結果如下:

 
+----+------------+-------+----------------+ 
| id | name  | score | game   | 
+----+------------+-------+----------------+ 
| 3 | player 3 | 30 | points_game1 | 
| 2 | player 2 | 25 | points_game2 | 
| 4 | player 4 | 20 | points_game3 | 
| 1 | player 1 | 10 | points_game1 | 
+----+------------+-------+----------------+ 
+0

你有沒有用過'UNPIVOT'看過? – Jodaka 2012-07-06 16:50:35

+0

能否詳細說明一下? iv'e從未在mysql中使用過這種方法 – 2012-07-06 21:14:35

+0

'UNPIVOT'讓我們列出列名並使其成爲行的一部分:例如,每個玩家最終會得到三行,每行有四列:id,name,game ,分。除了我剛纔意識到你在使用MySQL,並且MySQL中不支持「UNPIVOT」。抱歉。 http://forums.mysql.com/read.php?10,379790有一個好的解決辦法。 – Jodaka 2012-07-10 01:28:50

回答

0

下面的查詢回答你的問題:

SELECT 
    id, 
    name, 
    GREATEST(points_game1, points_game2, points_game3) AS score, 
    CASE 
    WHEN points_game1 = GREATEST(points_game1, points_game2, points_game3) THEN 'points_game1' 
    WHEN points_game2 = GREATEST(points_game1, points_game2, points_game3) THEN 'points_game2' 
    WHEN points_game3 = GREATEST(points_game1, points_game2, points_game3) THEN 'points_game3' 
    END AS game 
FROM 
    users 
ORDER BY 
    3 DESC 

有點粗,由於最大的重複性(... )計算。你可能希望把它放在子查詢中。

在任何情況下,請注意,由於ORDER BY在列上使用了一個函數,因此該查詢不會使用表上的任何索引 - 這會否定MySQL中的密鑰使用。

+0

謝謝!按照要求工作。你將如何改變它以將GREATEST置於子查詢中? – 2012-07-06 19:29:02

+0

(嗯,不能在此評論正確格式) 像這樣: ' \t SELECT \t ID, \t名, \t得分, \t CASE \t \t WHEN points_game1 =則得分 'points_game1' \t \t WHEN points_game2 =得分THEN'points_game2' \t \t WHEN points_game3 =得分THEN'points_game3' \t END AS遊戲 \t FROM( \t \t SELECT *,GREATEST(points_game1,points_game2,points_game3)AS評分從用戶 \t)sel_score \t ORDER BY \t得分降序 ' – 2012-07-07 03:17:33

+0

什麼是 「sel_score」 的呢?另外,哪一個更高效? – 2012-07-07 03:32:48