È necessario disporre di un riferimento al record corrente e quindi cercare progressivamente il record successivo in base alle colonne ordinate. L'esempio seguente presuppone che sia ordinato su
ORDER BY Active, DIN, NAME
Primo:
SELECT *
FROM TABLE
WHERE NAME LIKE '%X%' AND DIN LIKE '%%'
ORDER BY Active, DIN, Name
LIMIT 1;
Avanti:(assicurati di separare il CURR.ID = 6
e gli AND-OR con le parentesi appropriate! )
SELECT *
FROM TABLE T
INNER JOIN TABLE CURR ON CURR.ID = 6 # the current ID being viewed
AND ((T.Active = Curr.Active AND T.DIN = Curr.DIN AND T.NAME > Curr.Name)
OR (T.Active = Curr.Active AND T.DIN > Curr.DIN)
OR T.Active > Curr.Active)
WHERE T.NAME LIKE '%X%' AND T.DIN LIKE '%%'
ORDER BY T.Active, T.DIN, T.Name
LIMIT 1;
Un esempio funzionante presentato di seguito
create table products
(ID int, SEED int, NAME varchar(20), DIN varchar(10), ACTIVE int, DELETED int);
insert products values
(1, 0, 'Product #1', '004812', 1, 0),
(2, 0, 'Product #2', '004942', 0, 0),
(3, 0, 'Product #3', '004966', 1, 0),
(4, 0, 'Product #4', '007437', 1, 1),
(5, 2, 'Product #2', '004944', 0, 0),
(6, 2, 'Product #2', '004944', 1, 0);
SELECT *
FROM products
WHERE active = 1 AND deleted = 0
ORDER BY din DESC, ID desc;
Output:
"ID";"SEED";"NAME";"DIN";"ACTIVE";"DELETED"
"3";"0";"Product #3";"004966";"1";"0"
"6";"2";"Product #2";"004944";"1";"0"
"1";"0";"Product #1";"004812";"1";"0"
Se corrente è la riga con ID=6, il record successivo può essere recuperato utilizzando
SELECT T.*
FROM products T
INNER JOIN products curr on curr.ID = 6
AND ((T.din = curr.din and T.ID > curr.ID)
OR (T.din < curr.din))
WHERE T.active = 1 AND T.deleted = 0
ORDER BY T.din DESC, T.ID ASC
LIMIT 1;