MySQL按ID添加rownumbers

时间:2014-01-28 14:56:23

标签: mysql sessionid row-number

我有一个使用sessionID的表测试。我想对ID进行分组,并为每个ID的每条记录添加rownumber。我使用了MSSQL Row_Number() over(order by) in MySql并添加了一个if语句(每个session_ID分组)。但是,它不起作用。有谁知道为什么这不起作用?

SET @row:=0
SET @sessionID:=0

SELECT 
    session_ID
    @row:=if(@sessionID = session_ID, @row+1, 1) AS row_num
    @sessionID := session_ID
FROM test  

1 个答案:

答案 0 :(得分:1)

您需要row_num之后的逗号,并且需要order by

SET @row:=0;
SET @sessionID:=0;

SELECT 
    session_ID,
    @row:=if(@sessionID = session_ID, @row+1, 1) AS row_num,
    @sessionID := session_ID
FROM test
ORDER BY session_ID;

您可以将其写为单个查询:

SELECT session_ID,
       @row:=if(@sessionID = session_ID, @row+1, 1) AS row_num,
       @sessionID := session_ID
FROM test cross join
     (select @row := 0, @sessionID := 0)
ORDER BY session_ID;