2017-01-04 64 views
0

我創建了排名系統,因此我需要爲每個用戶設置排名位置。
我這樣做:sql - @curRow基於列

SELECT @curRow := @curRow + 1 AS position, 
       Sum(point_user.amount) AS points 
FROM  users u 
JOIN  point_user ON u.id = point_user.user_id 
JOIN (SELECT @curRow := 0) r 
GROUP BY 
u.id 
ORDER BY 
position ASC 

而且我越來越:

+----------+----------+ 
| position | points | 
+----------+----------+ 
|  1 | 86  | 
|  2 | 239  | 
|  3 | 45  | 
+----------+----------+ 

現在,我怎麼可以設置行號的基礎上,分?
是否應是這樣的:

+----------+----------+ 
| position | points | 
+----------+----------+ 
|  1 | 239  | 
|  2 | 86  | 
|  3 | 45  | 
+----------+----------+ 

UPDATE

SELECT (@curRow := @curRow + 1) as position, 
       points, 
       u2.id 
FROM (SELECT Sum(pu.amount) AS points 
     FROM users u JOIN 
      point_user pu 
      ON u.id = pu.user_id 
     GROUP BY u.id 
     ORDER BY points DESC 
) upu, users u2 
CROSS JOIN (
      SELECT @curRow := 0 
) params 
ORDER BY points DESC 

回答

3

在查詢中,它可能是足以改變ORDER BYORDER BY points DESC - 因爲這似乎是你的意圖。

但是,MySQL有一個已知的變量和GROUP BY問題。解決方案只是使用子查詢:

SELECT (@curRow := @curRow + 1) as position, points 
FROM (SELECT Sum(pu.amount) AS points 
     FROM users u JOIN 
      point_user pu 
      ON u.id = pu.user_id 
     GROUP BY u.id 
     ORDER BY points DESC 
    ) upu CROSS JOIN 
    (SELECT @curRow := 0) params 
ORDER BY points DESC; 
+0

太棒了!謝謝!但我還有一個問題 - 如何擴展這些附加列?例如。用戶ID等。我這樣做(更新問題),但我得到約1 600 000條記錄(應該是1129) – Vertisan

+0

內部'ORDER BY'可能被優化器忽略。你正在運行什麼版本?什麼'EXPLAIN EXTENDED SELECT ...; SHOW WARNINGS;'說? –

+0

@Vertisan。 。 。您可以將其擴展到其他列 - 實際上,您可以在子查詢中包含其他列。如果你的意思不止於此,你應該提出另一個問題,包括樣本數據和期望的結果。 –