0

我有一个表用户

Name     | Poin 
================== 
user1    | 20 
user2    | 30 
user3    | 80 
user4    | 60 
user5    | 10 
user6    | 85 

我有 SQL 查询

SELECT * 
FROM user 
ORDER BY poin

看起来,数据序列基于点。

但是我需要的是这样的数据(比如我是user1):

Position 1 : user6 - 85 point 
Position 2 : user3 - 80 point 
Position 3 : user4 - 60 point 

你是position 5 : user1 - 20 point


更新

我用这个 sql

SELECT x.name, x.position
FROM (SELECT t.user,
            @rownum := @rownum + 1 AS position
            FROM user t
           JOIN (SELECT @rownum := 0) r
           ORDER BY t.poin DESC) x
WHERE x.user ='用户1'

4

6 回答 6

1

这将给出当前排名user1

SELECT count(*) AS rank
FROM user
WHERE poin >= (SELECT poin FROM user WHERE name = 'user1')

这个查询的小问题是,如果另一个用户有相同的分数,它将被分配相同的排名——它是否正确,这是值得怀疑的。

如果您只想为每个用户添加排名,请使用以下命令:

SELECT
    @rank:=@rank+1 AS rank,
    name,
    poin
FROM user,
    (SELECT @rank:=0) r
ORDER BY poin DESC

您可以使用此查询的小变化来获取单个用户的排名,但避免出现相同的排名歧义问题:

SELECT *
FROM (
    SELECT
        @rank:=@rank+1 AS rank,
        name,
        poin
    FROM user,
        (SELECT @rank:=0) r
    ORDER BY poin DESC
) x
WHERE name = 'user1'
于 2013-02-05T10:31:41.000 回答
0

select * from user order by poin desc

希望这可以帮助

于 2013-02-05T10:28:15.833 回答
0

以下代码:

SELECT count(*) AS rank 
FROM user 
WHERE poin >= (SELECT poin FROM user  WHERE name = 'user1')

当 is 在不同的行中有双点时有问题。

于 2013-02-05T11:22:57.097 回答
0
SELECT  Name, 
        Poin, 
        @rowNum := @rowNum + 1 AS position
FROM    user
JOIN    (SELECT @rowNum := 0) r
ORDER BY poin;
于 2013-02-05T10:31:40.500 回答
0
SELECT * FROM user ORDER BY poin DESC

ORDERBY 关键字用于按指定列对结果集进行排序。

默认情况下,ORDER BY关键字按升序对记录进行排序。

如果要按降序对记录进行排序,可以使用DESC关键字。

SQL ORDER BY 语法

SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
于 2013-02-05T10:28:29.750 回答
-1
SELECT  Name, 
        Poin, 
        @rowNum := @rowNum + 1 AS position
FROM    user
JOIN    (SELECT @rowNum := 0) r
ORDER BY poin DESC;
于 2013-02-05T10:28:34.160 回答