根据id的mysql对行进行排名

时间:2012-10-25 07:43:10

标签: mysql

我有以下问题。

SET @rownum := 0;
SELECT result.rank, result.postid FROM (                    
                SELECT CASE @rownum 

                WHEN 5 THEN  @rownum:=1 ELSE @rownum:=@rownum + 1  END AS rank
                    ,c.postid

                FROM comments c
                ORDER BY c.postid DESC
                ) as result

它以下列形式返回结果。

      rank               postid
    ---------------------------------
      1                    199
      2                    199
      3                    199
      4                    199
      5                    198
      1                    198
      2                    198
      3                    198
      4                    198
      5                    198
      6                    198

现在我想更新此查询,以便根据postid.postid 199指定排名将从1到4排名,一旦它识别出新的postid已经出现,它应该再次从1排名到任何数字id包含的记录。

I want the count of rank for each postid to start from 1 and goto the number of times that postid is appearing.

修改

@lieven它仍然在检查此图片时出现问题。

正如您所看到的帖子172完成但等级仍在继续

2 个答案:

答案 0 :(得分:1)

您可以按多个字段订购:

ORDER BY c.postid DESC, c.rank

第一个优先级最高。

答案 1 :(得分:0)

您可以使用以下语句,但性能在任何大型表上都是不可靠的。

对于每条记录,执行一个子选择,得到count作为等于postid的等级,其中主键小于或等于当前记录的等级。如果你返回100条记录,实质上就会执行101条语句。

SQL语句(慢)

>     SELECT c.postid    
>            , (SELECT COUNT(*) 
>               FROM   comments 
>               WHERE  postid = c.postid 
>                      AND tempid <= c.tempid
>              ) AS rank
>     FROM   comments c
>     ORDER BY
>            c.postid

SQL语句(快速(呃))

>     SET @rank := 1;
>     
>     SELECT  c1.postid
>             , CASE WHEN c1.postid= c2.postid 
>               THEN @rank := @rank + 1 
>               ELSE @rank := 1 
>               END AS Rank
>     FROM    (
>               SELECT  c.postid
>                       , @rownum1 := @rownum1 + 1 AS rownum
>               FROM    comments c, (SELECT @rownum1 := 1) r       
>               ORDER BY
>                       c.postid
>             ) c1
>             LEFT OUTER JOIN (
>               SELECT  c.postid
>                       , @rownum2 := @rownum2 + 1 AS rownum
>               FROM    comments c, (SELECT @rownum2 := 1) r       
>               ORDER BY
>                       c.postid
>             ) c2 ON c2.postid = c1.postid AND c2.rownum = c1.rownum - 1
>      ORDER BY
>             c1.postid