1

我有以下查询。

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完成,但排名仍在继续

4

2 回答 2

1

您可以按多个字段排序:

ORDER BY c.postid DESC, c.rank

第一个具有最高优先级。

于 2012-10-25T07:47:44.707 回答
0

您可以使用以下语句,但在任何大表上性能都将是异常的。

对于每条记录,都会执行一个子选择,将其count作为 equal 的排名,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 语句 (fast(er))

>     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
于 2012-10-25T08:21:53.573 回答