Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 564
Dudo1985 Avatar asked Nov 07 '25 09:11

Dudo1985


2 Answers

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!

like image 142
Borgy Manotoy Avatar answered Nov 10 '25 06:11

Borgy Manotoy


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
like image 25
apomene Avatar answered Nov 10 '25 08:11

apomene