0

Simple question, but I can't seem to find a simple solution:

What is the most efficient way to get both the previous and next step unique HEX ID based on current step number given the below data:

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

For example:
Lets assume that the provided step is 3, how could I get the unique HEX ID of both 2 and 4?

Thanks!


EDIT
This is what I'm currently using, but it doesn't seem all that efficient to me??

SELECT
    nxt.stepnum AS NextStep,
    nxt.unqID AS NextUnqID,
    prv.stepnum AS PrevStep,
    prv.unqID AS PrevUnqID
FROM foo w,
(
 SELECT stepnum, unqID FROM foo WHERE stepnum > 3 ORDER BY stepnum LIMIT 1
) AS nxt
,
(
 SELECT stepnum, unqID FROM foo WHERE stepnum < 3 AND ORDER BY stepnum DESC LIMIT 1
) AS prv
WHERE w.stepnum = 3
NotJustClarkKent
  • 1,078
  • 1
  • 11
  • 25

1 Answers1

2

I modified your query. While its a bit nested, it should consist of quite simple index lookups for the sql engine (in theory...)

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
biziclop
  • 14,466
  • 3
  • 49
  • 65
  • I like the use of `MAX` and `MIN` -- the order / limit is what I didn't like about my query! I'm assuming that the nested selects is the only way to go for this problem then? – NotJustClarkKent Jun 22 '12 at 18:39
  • It would be nice if MySQL's dumbass optimizer could recognize such situations, but it probably doesn't. – biziclop Jun 22 '12 at 18:41
  • 1
    Fiddle fun, view execution plan (of course it might be different in real world): http://sqlfiddle.com/#!2/b61db/1 – biziclop Jun 22 '12 at 18:44
  • Ok, thanks biziclop. I like this modification so I'm going to roll with it. Thanks for the help! – NotJustClarkKent Jun 22 '12 at 18:44
  • Damn, ran into an issue: If there is no prev/next step I'm not getting a result. For example, in your fiddle set the step to `5` – NotJustClarkKent Jun 22 '12 at 18:54