Mysql – How to select an item, the one below and the one above in MYSQL

MySQL

I have a database with ID's that are non-integers like this:

b01
b02
b03
d01
d02
d03
d04
s01
s02
s03
s04
s05

etc. The letters represent the type of product, the numbers the next one in that group.

I'd like to be able to select an ID, say d01, and get b03, d01, d02 back. How do I do this in MYSQL?

Best Answer

Find your target row,

SELECT p.id FROM product WHERE id = 'd01'

and the row above it with no other row between the two.

LEFT JOIN product AS p1 ON p1.id > p.id    -- gets the rows above it

LEFT JOIN       -- gets the rows between the two which needs to not exist
        product AS p1a ON p1a.id > p.id AND p1a.id < p1.id

and similarly for the row below it. (Left as an exercise for the reader.)

In my experience this is also quite efficient.

    SELECT
        p.id, p1.id, p2.id
    FROM
        product AS p
    LEFT JOIN
        product AS p1 ON p1.id > p.id
    LEFT JOIN 
        product AS p1a ON p1a.id > p.id AND p1a.id < p1.id
    LEFT JOIN
        product AS p2 ON p2.id < p.id
    LEFT JOIN 
        product AS p2a ON p2a.id < p.id AND p2a.id > p2.id
    WHERE
        p.id = 'd01'
        AND p1a.id IS NULL
        AND p2a.ID IS NULL