我有这样一张桌子
+------+----------+------------+
| 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。
我怎样才能实现这个目标?
答案 0 :(得分:3)
尝试使用子查询:
SELECT *
FROM (
SELECT id,
@curRow := @curRow + 1 AS row_number
FROM srwk_esp_registration
JOIN (
SELECT @curRow := 0
) r
) sub
WHERE sub.ID = 22
答案 1 :(得分:2)
如果您不想声明变量(SET @rownum something)......
通常情况下,我的常规查询是
SELECT t.* FROM ticket t
我会在@i:=@i+1 as row_number,
之前或之后添加t.*
,并使用(SELECT @i:=0)
加入表格:
SELECT @i:=@i+1 as row_number, t.* FROM ticket t, (SELECT @i:=0) AS temp
尝试更改示例查询,希望它有所帮助。
祝你好运!