我希望从表中选择时编号的数据行。问题是,我不需要顺序编号,但它应该从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;
如何让它正常工作?
答案 0 :(得分:3)
改编自这个答案:With MySQL, how can I generate a column containing the record index in a table?
SELECT MOD(@curRow := @curRow + 1, 3) AS row_number
FROM mytable m
JOIN (SELECT @curRow := 0) r;
答案 1 :(得分:1)
如果你只需要选择并假设有一个列,比如说“id”,这是顺序的,那么下面的查询应该会有所帮助:
SELECT IF ((id%3) = 0, 3 , (id%3)) AS new_id, <other columns> FROM <table_name>;
希望它有所帮助...