Mysql 获取行号
Mysql get row number
我有一个table这样的
+------+----------+------------+
| id | 1_value | 2_value |
+------+----------+------------+
| 3 | foo1 | other |
| 10 | fooX | stuff |
| 13 | fooJ | here |
| 22 | foo7 | and |
| 31 | foou | here |
+------+----------+------------+
我想得到的是有行号
我试过这样做
SELECT id, @curRow := @curRow + 1 AS row_number
FROM table
JOIN (SELECT @curRow := 0) r
确实有效...
+------+--------------+
| id | row_number |
+------+--------------+
| 3 | 1 |
| 10 | 2 |
| 13 | 3 |
| 22 | 4 |
| 31 | 5 |
+------+--------------+
但是如果我尝试 select 特定行呢?
SELECT id, @curRow := @curRow + 1 AS row_number
FROM srwk_esp_registration
JOIN (SELECT @curRow := 0) r
WHERE ID = 22
在这种情况下,row_number是1,但应该是4。
我怎样才能做到这一点?
尝试使用子查询:
SELECT *
FROM (
SELECT id,
@curRow := @curRow + 1 AS row_number
FROM srwk_esp_registration
JOIN (
SELECT @curRow := 0
) r
) sub
WHERE sub.ID = 22
如果你不想声明一个变量(SET @rownum something)...
通常,我的正常查询是
SELECT t.* FROM ticket t
我会在 t.*
之前或之后添加 @i:=@i+1 as row_number,
并加入 table 和 (SELECT @i:=0)
:
SELECT @i:=@i+1 as row_number, t.* FROM ticket t, (SELECT @i:=0) AS temp
尝试更改示例查询,希望它能有所帮助。
祝你好运!
我有一个table这样的
+------+----------+------------+
| id | 1_value | 2_value |
+------+----------+------------+
| 3 | foo1 | other |
| 10 | fooX | stuff |
| 13 | fooJ | here |
| 22 | foo7 | and |
| 31 | foou | here |
+------+----------+------------+
我想得到的是有行号
我试过这样做
SELECT id, @curRow := @curRow + 1 AS row_number
FROM table
JOIN (SELECT @curRow := 0) r
确实有效...
+------+--------------+
| id | row_number |
+------+--------------+
| 3 | 1 |
| 10 | 2 |
| 13 | 3 |
| 22 | 4 |
| 31 | 5 |
+------+--------------+
但是如果我尝试 select 特定行呢?
SELECT id, @curRow := @curRow + 1 AS row_number
FROM srwk_esp_registration
JOIN (SELECT @curRow := 0) r
WHERE ID = 22
在这种情况下,row_number是1,但应该是4。
我怎样才能做到这一点?
尝试使用子查询:
SELECT *
FROM (
SELECT id,
@curRow := @curRow + 1 AS row_number
FROM srwk_esp_registration
JOIN (
SELECT @curRow := 0
) r
) sub
WHERE sub.ID = 22
如果你不想声明一个变量(SET @rownum something)...
通常,我的正常查询是
SELECT t.* FROM ticket t
我会在 t.*
之前或之后添加 @i:=@i+1 as row_number,
并加入 table 和 (SELECT @i:=0)
:
SELECT @i:=@i+1 as row_number, t.* FROM ticket t, (SELECT @i:=0) AS temp
尝试更改示例查询,希望它能有所帮助。
祝你好运!