0

我想要从表中选择后编号的数据行。问题是,我不需要顺序编号,但它应该从 1 到 3 编号,直到最后,如下所示:

1 | first row
2 | second row
3 | third row 
1 | fourth row
2 | and
3 | ....
1
2
3

我正在尝试这个查询,但它不能正常工作:

mysql -> SET @n = 0;
-> SELECT 
CASE 
    WHEN nnn = 3 THEN  @n := 0
        ELSE nnn
    END
FROM  (
    SELECT @n := @n + 1 AS nnn FROM mytable
) AS t;

如何使其正常工作?

4

2 回答 2

3

改编自这个答案: 使用 MySQL,如何在表中生成包含记录索引的列?

SELECT  MOD(@curRow := @curRow + 1, 3) AS row_number
FROM    mytable m
JOIN    (SELECT @curRow := 0) r;
于 2012-09-17T12:46:49.017 回答
1

如果您只需要选择并假设有列,比如“id”,那是顺序的,那么下面的查询应该会有所帮助:

SELECT IF ((id%3) = 0, 3 , (id%3)) AS new_id, <other columns> FROM <table_name>;

希望能帮助到你...

于 2012-09-17T13:26:24.290 回答