Du måste ha en referens till den aktuella posten och sedan gradvis leta efter nästa post baserat på de sorterade kolumnerna. Exemplet nedan antar att det är sorterat på
ORDER BY Active, DIN, NAME
Först:
SELECT *
FROM TABLE
WHERE NAME LIKE '%X%' AND DIN LIKE '%%'
ORDER BY Active, DIN, Name
LIMIT 1;
Nästa:(se till att du separerar CURR.ID = 6
och OCH-ELLER med rätt parentes! )
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;
Ett fungerande exempel presenteras nedan
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"
Om aktuell är raden med ID=6 kan nästa post hämtas med
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;