数据库
首页 > 数据库> > Mysql获取行号

Mysql获取行号

作者:互联网

我有一张这样的桌子

+------+----------+------------+
|   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  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

标签:row-number,mysql,row
来源: https://codeday.me/bug/20190828/1749348.html