MySQL简单行号增量计数器

时间:2014-08-29 03:48:01

标签: mysql sql random row-number

我正在尝试在SQL select子句中生成增量计数器(下面的查询中的列“rownum”)。每次新用户切换时,计数器应重新开始。

    SELECT * FROM (
    SELECT CONCAT('    ',g.node1,'    ',g.node2),
    @r:= CASE WHEN @g = g.`user` THEN @r +1 ELSE 1 END rownum,
    @g:= g.`user` user_group
    FROM sn.sn_graph_reduced g
    CROSS JOIN (SELECT @g:=0,@r:=0) t2
    ORDER BY `user` , RAND() 
    ) t
    WHERE rownum <= 100 

但是,上面的代码片段返回行号,并且由于记录是随机采样的,因此行号不是增量的。 我需要的是返回的每一行的简单计数器(1,2,3 ....)。 感谢

2 个答案:

答案 0 :(得分:2)

尝试将变量放在内联视图之外:

SELECT t.*,
       @r:= CASE WHEN @t = t.`user` THEN @r +1 ELSE 1 END rownum,
       @t:= t.`user` user_group
FROM    (
        SELECT CONCAT('    ',g.node1,'    ',g.node2), g.`user`
        FROM sn.sn_graph_reduced g
        ORDER BY `user` , RAND()
        ) t
CROSS JOIN (SELECT @t:=0,@r:=0) t2
where rownum <= 100

答案 1 :(得分:0)

增加行号的方法不直接处理RAND(),因此使用rand()中的值作为列。同时启动@g为''不为零,然后你需要一个最终的ORDER BY。

SELECT
      *
FROM (
            SELECT
                  CONCAT('    ', g.node1, '    ', g.node2) AS node_concat
                , @r:= IF(@g = g.`user`, @r + 1, 1)        AS rownum
                , @g:= g.`user`                            AS user_group
            FROM (
                   SELECT *, rand() AS R FROM sn_graph_reduced
                   ) g
                  CROSS JOIN ( SELECT @g:= '' ,@r:= 1 ) t2
            ORDER BY
                  `user`
                , R
      ) t
WHERE rownum <= 100
ORDER BY
       user_group
     , rownum
;

请参阅:This SQLfiddle