0

I would like data rows numbered upon selecting from a table. Problem is that, I need not sequential numbering, but it should be numbered from 1 to 3 and so to the end, like below:

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

I'm trying this query, but it does not work correctly:

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;

How to make it working correctly?

Be Brave Be Like Ukraine
  • 7,596
  • 3
  • 42
  • 66
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

2 Answers2

3

Adapted from this answer: 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;
Community
  • 1
  • 1
Cargo23
  • 3,064
  • 16
  • 25
1

If you only need to select and assuming that there is column, say "id", that is sequential, then following query should help:

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

Hope it helps...

jsist
  • 5,223
  • 3
  • 28
  • 43