如何使用mysql查询显示排名

时间:2014-02-25 07:15:25

标签: php mysql sql

user_id | date | point
    1      20      4
    2      20      3
    3      20      2
    1      21      1
    2      21      3
    3      21      5
    1      23      2
    2      23      4
    3      23      5

并查询:

SELECT user_id, SUM(point) AS point, @row:=@row+1 rank FROM users GROUP BY user_id

如何在此查询中显示排名?

6 个答案:

答案 0 :(得分:2)

首先你需要将@row声明为变量

set @row=0; select user_id,SUM(point) as point,@row := @row + 1 as rank from users GROUP BY user_id order by SUM(point) desc;

这样的东西

答案 1 :(得分:0)

试试这个

SET @row=0;
SELECT user_id, SUM(point) AS point, @row:=@row+1 rank FROM users GROUP BY user_id

答案 2 :(得分:0)

您可以使用以下方式解决声明部分:

SELECT user_id, SUM(point) AS point, @row:=@row+1 rank FROM users, (SELECT @row := 0) r GROUP BY user_id

答案 3 :(得分:0)

我想你要把它写成:

SELECT user_id, SUM(point) AS point, @row:=@row+1 AS rank FROM users GROUP BY user_id JOIN (SELECT @row := 0) r;

答案 4 :(得分:0)

试试这个..

SELECT user_id,points, @row:=@row+1 AS Row 
from (
  SELECT user_id, 
    SUM(point) AS points  rank 
  FROM users 
  GROUP BY user_id 
  Sort by points);

答案 5 :(得分:0)

应该有一个AS来对别名进行排序,并按顺序排序,以便按正确的顺序排序: -

SELECT user_id, SUM(point) AS point, @row:=@row+1 AS rank 
FROM users 
CROSS JOIN (SELECT @row:=0) Sub1
GROUP BY user_id
ORDER BY point DESC