4

I've a table like this

+------+----------+------------+
|   id |  1_value |   2_value  |
+------+----------+------------+
|    3 |   foo1   |   other    |
|   10 |   fooX   |   stuff    |
|   13 |   fooJ   |   here     |
|   22 |   foo7   |   and      |
|   31 |   foou   |   here     |
+------+----------+------------+

What I want to get is to have the row number

I've tried to do something like this

SELECT  id, @curRow := @curRow + 1 AS row_number
FROM    table
JOIN    (SELECT @curRow := 0) r

and it work indeed...

+------+--------------+
|   id |  row_number  | 
+------+--------------+
|    3 |   1          | 
|   10 |   2          |
|   13 |   3          |
|   22 |   4          |
|   31 |   5          |
+------+--------------+

but what if I try to select a specific row?

SELECT  id, @curRow := @curRow + 1 AS row_number
FROM    srwk_esp_registration
JOIN    (SELECT @curRow := 0) r
WHERE ID = 22

In this case, row_number is 1, but it should be 4.

How can I acheive this?

Dudo1985
  • 177
  • 2
  • 3
  • 12

2 Answers2

6

If you do not want to declare a variable (SET @rownum something)...

Normally, my normal query is

SELECT t.* FROM ticket t

I would add @i:=@i+1 as row_number, before or after t.* and join the table with (SELECT @i:=0):

SELECT @i:=@i+1 as row_number, t.* FROM ticket t, (SELECT @i:=0) AS temp

try to alter the sample query and hope it would help.

Good Luck!

Borgy Manotoy
  • 1,960
  • 5
  • 27
  • 42
5

Try with Sub - query:

SELECT * 
FROM (
    SELECT id,
        @curRow := @curRow + 1 AS row_number
    FROM srwk_esp_registration
    JOIN (
        SELECT @curRow := 0
        ) r
    ) sub
WHERE sub.ID = 22
Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
apomene
  • 14,282
  • 9
  • 46
  • 72