Search code examples
mysqlrowrow-number

Mysql get row number


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?


Solution

  • 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