根据当前步骤编号获取上一步和下一步唯一ID

时间:2012-06-22 18:12:11

标签: mysql sql

简单的问题,但我似乎无法找到一个简单的解决方案:

根据以下数据,根据当前步骤编号获得前一步和下一步唯一HEX ID的最有效方法是什么:

---- + ------------- + ----------------
ID | UnqID | STEPNUM |
---- + ------------- + ----------------
21 | BCDEF | 1 |
22 | GhIjKL | 2 |
23 | MnOPq | 3 |
24 | RsTuV | 4 |
25 | wXyZa | 5 |
---- + ------------- + ----------------

例如:
让我们假设提供的步骤为3,我怎样才能获得2和{{1}的唯一HEX ID }?

谢谢!


修改
这就是我目前正在使用的东西,但它对我来说似乎并不那么高效?

4

1 个答案:

答案 0 :(得分:2)

我修改了你的查询。虽然它有点嵌套,但应该包含sql引擎非常简单的索引查找(理论上......)

SELECT
    nxt.stepnum AS NextStep,
    nxt.unqID   AS NextUnqID,
    prv.stepnum AS PrevStep,
    prv.unqID   AS PrevUnqID

FROM (SELECT NULL) AS dummy -- dummy table to LEFT JOIN to

LEFT JOIN
( SELECT stepnum, unqID FROM foo
  WHERE stepnum = (SELECT MIN(stepnum)
                   FROM foo
                   WHERE stepnum > 5 )
) AS nxt ON true

LEFT JOIN
( SELECT stepnum, unqID FROM foo
  WHERE stepnum = (SELECT MAX(stepnum)
                   FROM foo
                   WHERE stepnum < 5 )
) AS prv ON true